HttpClient 4 Cookbook

1. Overview

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

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 the 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:

  • HttpClient 4 – Get the Status Code
  • HttpClient – Set Custom Header

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 over on GitHub.

This is a Maven based project, so it should be easy to import and run as it is.

Related posts:

Java Program to Convert a Decimal Number to Binary Number using Stacks
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
How to Delay Code Execution in Java
Java Program to Implement Fenwick Tree
Error Handling for REST with Spring
Guide to DelayQueue
Java Program to Implement Borwein Algorithm
Java Program to Perform integer Partition for a Specific Case
Runnable vs. Callable in Java
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
Java Program to Implement RoleUnresolvedList API
Multi Dimensional ArrayList in Java
Java Program to Generate a Random Subset by Coin Flipping
Java Program to Implement vector
Convert Character Array to String in Java
Hướng dẫn Java Design Pattern – Adapter
Java Program to Implement Shell Sort
Java Program to Implement Fermat Factorization Algorithm
Java Concurrency Interview Questions and Answers
Set Interface trong Java
Sử dụng Fork/Join Framework với ForkJoinPool trong Java
Lớp Arrarys trong Java (Arrays Utility Class)
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Java Program to Decode a Message Encoded Using Playfair Cipher
Java Program to Implement Sieve Of Eratosthenes
Instance Profile Credentials using Spring Cloud
Introduction to PCollections
Spring MVC and the @ModelAttribute Annotation
Java Program to find the maximum subarray sum O(n^2) time(naive method)
Java Program to Implement RoleList API
Java Program to Find Location of a Point Placed in Three Dimensions Using K-D Trees