Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

1. Overview

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

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 is 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.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

HTTPClient footer
Comments are closed on this article!