I usually post about HTTP stuff on Twitter - you can follow me there:

1. Overview

This cookbook shows how to use the Apache HttpClient 4 in a variety of examples and usecases.

The focus is on HttpClient 4.3.x and above, so some of the examples may not work with the older versions of the API.

The format of the cookbook is example focused and practical – no extraneous details and explanations necessary.

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

create the http client

CloseableHttpClient client = HttpClientBuilder.create().build();

send basic GET request

instance.execute(new HttpGet("http://www.google.com"));

get the Status Code of the HTTP Response

CloseableHttpResponse response = instance.execute(new HttpGet("http://www.google.com"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

get the Media Type of the response

CloseableHttpResponse response = instance.execute(new HttpGet("http://www.google.com"));
String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
assertThat(contentMimeType, equalTo(ContentType.TEXT_HTML.getMimeType()));

get the body of the response

CloseableHttpResponse response = instance.execute(new HttpGet("http://www.google.com"));
String bodyAsString = EntityUtils.toString(response.getEntity());
assertThat(bodyAsString, notNullValue());

configure the timeout on a request

@Test(expected = SocketTimeoutException.class)
public void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() 
    throws ClientProtocolException, IOException {
    RequestConfig requestConfig = RequestConfig.custom()
      .setConnectionRequestTimeout(1000).setConnectTimeout(1000).setSocketTimeout(1000).build();
    HttpGet request = new HttpGet(SAMPLE_URL);
    request.setConfig(requestConfig);
    instance.execute(request);
}

configure timeout on the entire client

RequestConfig requestConfig = RequestConfig.custom().
    setConnectionRequestTimeout(1000).setConnectTimeout(1000).setSocketTimeout(1000).build();
HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig);

send a POST request

instance.execute(new HttpPost(SAMPLE_URL));

add parameters to a request

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("key1", "value1"));
params.add(new BasicNameValuePair("key2", "value2"));
request.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));

configure how redirect are handled for an HTTP Request

CloseableHttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build();
CloseableHttpResponse response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));

configure the headers for a request

HttpGet request = new HttpGet(SAMPLE_URL);
request.addHeader(HttpHeaders.ACCEPT, "application/xml");
response = instance.execute(request);

get the headers from response

CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL));
Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
assertThat(headers, not(emptyArray()));

close/release resources

response = instance.execute(new HttpGet(SAMPLE_URL));
try {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        instream.close();
    }
} finally {
    response.close();
}

3. Go Deep into HttpClient

The HttpClient library is quite a powerful tool if used correctly – if you want to start exploring what the client can do – check out some of the tutorials:

You can also dig a lot deeper into the HttpClient by exploring the entire series.

4. Conclusion

This format is a bit different from how I usually structure my articles – I’m publishing some of my internal development cookbooks on a given topic – on Google Guava, Hamcrest andMockito – and now HttpClient. The goal is to have this information readily available online – and to add to it whenever I run into a new useful example.

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 usually post about HTTP stuff on Twitter - you can follow me there:


  • webiyo

    Please add an example which makes the use of HTTP Connection Pool 🙂

    • I did think about adding that in – but the PoolingHttpClientConnectionManager is used by default (as opposed to older versions of the library) – so it does make use of a connection pool out of the box.
      Cheers,
      Eugen.

  • Jimmy Bway

    Thx very usefull 😉

  • donald

    Thank you so much. Really helpful

  • KennethMark

    Really helpful examples as HttpClient 4 being very different from version 3. Thanks a lot !

    • Glad you’re finding the article useful. Indeed – HttpClient 4 is entirely different – and there are still a lot of examples using 3.x out there – which is part of the reason I wrote all of these 4.x articles. Cheers,
      Eugen.

  • Peter

    A very useful article, thanks. Just one update that might be useful – in your ‘configure timeout on the entire client’ section I noticed when I implemented it that timeouts need to be defined in millisecs (i.e 50000), not seconds (50).

    • Hey Peter – nice catch. I addressed that in my HttpClient timeout article but didn’t update the cookbook. It’s updated now – thanks for pointing it out. Cheers,
      Eugen.

      • David Patterson

        One semi-unrelated change that came in in about Java 5-ish is the ability to use the underscore character in numbers. So that in stead of writing

        RequestConfig requestConfig = RequestConfig.custom()
        .setConnectionRequestTimeout(1000)
        .setConnectTimeout(1000)
        .setSocketTimeout(1000).build();you can write

        RequestConfig requestConfig = RequestConfig.custom()
        .setConnectionRequestTimeout(1_000)
        .setConnectTimeout(1_000)
        .setSocketTimeout(1_000).build();

        (the newlines were just to prevent the line from being too long, not a suggestion).

        I find it easier to read numbers with a bunch of zeros using these as spacers. Java ignores them completely.

  • paul

    Now that we have a standard rest client as per jsr 311. Is there a benefit using other http java client?
    When would I use one vs other if at all

    • Hey Paul – I would say that you should use whatever tool does the job. My personal preference is towards an actively maintained tool where I can contribute changes, ask for bug fixes, etc – that kind of project will evolve and mature much better than one focused on standardization, especially through the faulty JSR process. But again – that’s just a personal opinion – hope that makes sense. Cheers,
      Eugen.

  • Arvind Subramanian

    Helpful article. Is there any recommended practice to integrate HttpClient with Spring Frawework.

    • Hey Arvind – there’s no special way to integrate the client into Spring – you just need to define the HttpClient as a bean in a Spring configuration and then inject it wherever you need to use it. Cheers,
      Eugen.

  • Antonio Perez Dieppa

    Useful article about Apache HttpClient. Thanks.
    However it would be nice to mention somewhere some other ways of having a http client with Spring such as Feing client from Netflix. Which I find much more convenient by far.

    Antonio