Updated: 2018-06-27
  • Website
  • HttpComponents Client is a successor of and replacement for Commons HttpClient 3.x


URI is defined in JDK; HttpComponents provides a URIBuilder to build up an URI, following the builder pattern.

import org.apache.http.client.utils.URIBuilder;

URIBuilder builder = new URIBuilder()
URI uri =;


To create a GET request: create a HttpGet from URI

import org.apache.http.client.methods.HttpGet;

URI uri = ...;
HttpGet httpGet = new HttpGet(uri);

We will show how to submit the request and get the response shortly.


Create an HttpPost by URI

HttpPost httpPost = new HttpPost(uri);

or by String

HttpPost httpPost = new HttpPost("http://" + host + ":" + port + endpoint);

Unlike HttpGet, data need to be added to the request body:

List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair(name, value));
nvps.add(new BasicNameValuePair(...., .....));
nvps.add(new BasicNameValuePair(...., .....));

httpPost.setEntity(new UrlEncodedFormEntity(nvps));


HttpClient will handle the submission of the requests

To Create an HttpClient: version >= 4.3

import org.apache.http.client.methods.CloseableHttpResponse;

CloseableHttpClient httpClient = HttpClients.createDefault();

version <= 4.2

import org.apache.http.client.HttpClient;

HttpClient httpClient = new DefaultHttpClient();


version >= 4.3

CloseableHttpResponse response = httpClient.execute(httpGet);

version <= 4.2

HttpResponse response = httpClient.execute(httpPost);

Put Everything Together

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
        // Deal with errors
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(...);

        // Content String
        String content = IOUtils.toString(response.getEntity().getContent());

Fluent API

Simple fluent API to get a response string from a GET request:

import org.apache.http.client.fluent.Request;

String responseString = Request.Get(uri).execute().returnContent().asString();