Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating from httpclient4 to httpclient5 - Unable to use setSSLContext

We are trying to upgrade the httpclient from 4 to 5. As a part of the upgrade, we have changed the imports accordingly. But, the code uses Httpclientbuilder and sets the sslcontext. As per the documentation from apache, they have removed the setsslcontext from the Httpclientbuilder methods and I have not found any alternative.

The error says The method setSSLContext(sslcontext) is undefined for the type HttpClientBuilder.

The code is as follows:


import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;

SSLContext sslcontext = SSLContext.getDefault();
HttpClient httpclient = HttpClientBuilder.create().setSSLContext(sslcontext).build();
ClientHttpRequestFactory reqFac = new HttpComponentsClientHttpRequestFactory(httpclient);
like image 366
Ravi Avatar asked Jan 01 '26 07:01

Ravi


2 Answers

Here ist the replacement we use:

HttpClientBuilder clientBuilder = HttpClients.custom();
final SSLContext sslContext = createSslContext();
final ConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier());
final Registry<ConnectionSocketFactory> socketFactoryRegistry =
                    RegistryBuilder.<ConnectionSocketFactory> create()
                            .register("https", sslsf)
                            .register("http", new PlainConnectionSocketFactory())
                            .build();
final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
clientBuilder.setConnectionManager(connectionManager);
like image 122
xtermi2 Avatar answered Jan 06 '26 12:01

xtermi2


Based on the migration guide, you can use the PoolingHttpClientConnectionManager to set the SSL context.

For example:

import org.apache.hc.client5.http.impl.classic.HttpClients
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder
import org.apache.http.ssl.SSLContextBuilder


SSLContext sslContext = SSLContext.getDefault();
PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
    .setSSLSocketFactory(
        SSLConnectionSocketFactoryBuilder.create()
            .setSslContext(sslContext)
            .build()
        )
    .build()
CloseableHttpClient httpClient = HttpClients
    .custom()
    .setConnectionManager(connectionManager)
    .build()
like image 24
Gex Avatar answered Jan 06 '26 10:01

Gex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!