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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay