DEV Community

Jonathan U
Jonathan U

Posted on

How to make Apache's CloseableHttpAsyncClient explicitly use HTTP/1 or HTTP/2

In this tutorial, we'll demonstrate how to explicitly use HTTP/1 or HTTP/2 in Apache's CloseableHttpAsyncClient, a base implementation of HttpAsyncClient that also implements ModalClosable.

You'll need to have this dependency to your pom.xml:

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3.1</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Deprecated Way

In earlier versions of httpclient5, the HttpAsyncClientBuilder allowed you to use setVersionPolicy(org.apache.hc.core5.http2.HttpVersionPolicy versionPolicy), where you could pass in HttpVersionPolicy.FORCE_HTTP_1 or HttpVersionPolicy.FORCE_HTTP_2. For example:

final CloseableHttpAsyncClient client = HttpAsyncClients
        .custom()
        .useSystemProperties()
        .setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_1) //Deprecated
        .build();
Enter fullscreen mode Exit fullscreen mode

However, in recent versions of httpclient5, setVersionPolicy is deprecated.

Best Practice Way

Now, their documentation says that we should use TlsConfig and connection manager methods instead.

Here's an example:

TlsConfig tlsHttp1Config = TlsConfig.copy(TlsConfig.DEFAULT).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_1).build();
//Create a default connection manager
PoolingAsyncClientConnectionManager connectionManager = new PoolingAsyncClientConnectionManager();
connectionManager.setDefaultTlsConfig(tlsHttp1Config);

final CloseableHttpAsyncClient client = HttpAsyncClients
        .custom()
        .useSystemProperties()
        .setConnectionManager(connectionManager)
        .build();
Enter fullscreen mode Exit fullscreen mode

I hope these examples help if you ever need to use an explicit version of HTTP for your AsyncHttpClients.

Top comments (0)