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>
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();
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();
I hope these examples help if you ever need to use an explicit version of HTTP for your AsyncHttpClients.
Top comments (0)