I am making a simple request for a file using HttpClient from the Apache Commons. Here is my current code:
httpclient = new DefaultHttpClient();
httpget = new HttpGet(location);
context = new BasicHttpContext();
response = httpclient.execute(httpget, context);
entity = response.getEntity();
What would I need to do to cancel this request in the middle of the download?
We can use the AbortController object and the associated AbortSignal with the Fetch API to make cancelable HTTP requests. Once the AbortSignal is sent, the HTTP request is canceled and won't be sent if the cancellation signal is sent before the HTTP request is done.
A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource.
My question is about safety of checking cancellationToken status in another thread respect of the main thread of the job . Cancellation tokens are generally thread safe by design so passing them between threads and checking them should not be a problem.
You can use httpget.abort()
method to abort the request mid way.
See example here
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