我正在使用HttpURLConnection下载文件。我可以取消从另一个线程下载吗?如果没有,我应该使用哪种文件下载方法?
最佳答案
我的建议是使用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();
如果需要关闭多个线程之间的多个连接,则可以重用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();