Apaches fluent httpclient API is a facade API to simplify the httpclients usage for standard use cases. It’s also better readable and results in cleaner code. In this post we’ll see how to use a custom SSLContext with the fluent API. We’ll use the new 5.0 version because it contains some changes compared to 4.x.

Using the Fluent API

First of all we should import the library:

for maven:

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5-fluent</artifactId>
    <version>5.0.3</version>
</dependency>

for gradle:

compile 'org.apache.httpcomponents.client5:httpclient5-fluent:5.0.3'

A simple get request with the fluent API looks like:

Request.Get("https://blog.jdriven.com/")
        .execute()
        .returnContent().asString();

As the libraries name suggests: it’s fluent, simple and readable. But if we’d want to make a request to a host with for example self signed certificates, we’d need a custom HttpClient configured with a custom SSLContext.

Setting up an HttpClient

In apaches HttpClient v4.x the SSLContext would be set on an HttpClient through an SSLConnectionSocketFactory.

Like so:

        // version 4.x
        final SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(null, new TrustAllStrategy())
                .build();

        final SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(csf)
                .evictExpiredConnections()
                .build();

In version 5.0 this is done through an HttpClientConnectionManager:

    // version 5.0
    try {
        final SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(null, new TrustAllStrategy())
                .build();
        final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create()
                .setSslContext(sslcontext)
                .build();
        final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
                .setSSLSocketFactory(sslSocketFactory)
                .build();
        return HttpClients.custom()
                .setConnectionManager(cm)
                .evictExpiredConnections()
                .build();

    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        logger.error(e.getMessage());
    }

Using our custom HttpClient

Using our custom HttpClient is as simple as passing it to the execute method:

Request.Get("https://blog.jdriven.com/")
        .execute(httpClient)
        .returnContent().asString();

Conclusion

Although apaches documentation says that the fluent api is intended for simple use cases that do not require the full flexibility of HttpClient.

We can still use the full flexibility of HttpClient combined with the readability of Fluent API.

shadow-left