我的建议是使用HttpClient而不是HttpUrlConnection.它在许多方面都是一个更好的图书馆.
然后,您可以使用:
final SimpleHttpConnectionManager connectionManager =
new SimpleHttpConnectionManager();
final HttpClient client = new HttpClient(connectionManager);
// ... and when it's time to close the connection from another thread
connectionManager.shutdown();
Run Code Online (Sandbox Code Playgroud)
如果需要跨多个线程关闭多个连接,可以重用一个HttpClient实例,并以类似的方式一次性关闭它们:
static MultiThreadedHttpConnectionManager connectionManager =
new MultiThreadedHttpConnectionManager();
// HttpClient instance that can be shared across threads and create multiple connections
static HttpClient client = new HttpClient(connectionManager);
// ... and when it's time to close connections
connectionManager.shutdown();
Run Code Online (Sandbox Code Playgroud)