I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

This quick tutorial shows how to cancel a HTTP Request with the Apache HttpClient 4.

This is especially useful for potentially long running requests, or large download files that would otherwise unnecessarily consume bandwidth and connections.

If you want to dig deeper and learn other cool things you can do with the HttpClient – head on over to the main HttpClient tutorial.

2. Abort a GET Request

To abort an ongoing request, the client can simply use:

request.abort();

This will make sure that the client doesn’t have to consume the entire body of the request to release the connection:

@Test
public void whenRequestIsCanceled_thenCorrect() 
  throws ClientProtocolException, IOException {
    HttpClient instance = HttpClients.custom().build();
    HttpGet request = new HttpGet(SAMPLE_URL);
    HttpResponse response = instance.execute(request);

    try {
        System.out.println(response.getStatusLine());
        request.abort();
    } finally {
        response.close();
    }
}

3. Conclusion

This article illustrated how to abort an ongoing request with the HTTP client. Another option to stop long running requests if to make sure that they will time out.

The implementation of all these examples and code snippets can be found in my github project – this is an Eclipse based project, so it should be easy to import and run as it is.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS

Sort by:   newest | oldest | most voted
Abhijeet
Guest

Awesome never knew about it’s existence. Thanks. http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/methods/AbstractExecutionAwareRequest.html#abort()

It’s kind-off out of topic here, Can you share more about it’s(abort) implementation on the server-side.

Eugen Paraschiv
Guest

So, the Android version of the library should be similar, but I haven’t done Android work in a long wile so I’m not sure if it’s identical or not.

wpDiscuz