Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel an HttpClient request

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?

like image 591
Ben Kulbertis Avatar asked Mar 23 '11 02:03

Ben Kulbertis


People also ask

Can HTTP request be Cancelled?

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.

What is a cancellation token C#?

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.

Is CancellationTokenSource thread safe?

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.


1 Answers

You can use httpget.abort() method to abort the request mid way.

See example here

like image 57
Suresh Kumar Avatar answered Nov 15 '22 16:11

Suresh Kumar