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.

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 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:


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


1. Overview

This cookbook shows how to use the Apache HttpClient 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()
    HttpGet request = new HttpGet(SAMPLE_URL);

configure timeout on the entire client

RequestConfig requestConfig = RequestConfig.custom().
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();
} finally {

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 and Mockito – 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.

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


HTTPClient footer
Comments are closed on this article!