I'm using HttpURLConnection to download a file. Can I cancel the download from another thread? If not, what method for file download should I use?
My suggestion would be to use HttpClient instead of HttpUrlConnection. It's a better library in many respects.
Then, you could use:
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();
If you need to close multiple connections across multiple threads, you can reuse one instance of HttpClient and close them all in one go in a similar fashion:
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();
You can use the InterruptedException in conjunction with Tasks/Executors. Your spawned thread should be able to catch InterruptedException by wrapping the try/catch around the HttpURLConnection method that's doing the download. Java Concurrency In Practice, chapters 6 and 7 are relevant. Particularly 7.2 "Stopping a thread-based service".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With