httpclientapache-httpclient-5.x

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);

Solution

  • 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);