HttpComponents

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

URIBuilder

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

import java.net.URI;
import org.apache.http.client.utils.URIBuilder;

URIBuilder builder = new URIBuilder()
                .setScheme("http")
                .setHost(host)
                .setPort(port)
                .setPath(endpoint)
                .addParameter(...)
                .addParameter(...);
URI uri = builder.build();

HttpGet

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.

HttpPost


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

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();

HttpResponse

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();