随时从其他线程取消文件下载

fhu*_*cho 15 java

我正在使用HttpURLConnection下载文件.我可以从其他线程取消下载吗?如果没有,我应该使用什么方法下载文件?

Ole*_*boy 6

我的建议是使用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)