javaapache-httpcomponentsapache-httpclient-5.x

Migrating apache http client 5 from 5.3 to 5.4 trust all hosts and certificates deprecation replacement


I have upgraded from apache http client 5.3.x to 5.4.x.

The below code works fine

var sslContext = SSLContexts.custom()
        .loadTrustMaterial(null, TrustAllStrategy.INSTANCE)
        .build();

SSLConnectionSocketFactory sslConnSocketFactory = 
    SSLConnectionSocketFactoryBuilder.create()
        .setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
        .setSslContext(sslContext)
        .build();

var connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
        .setSSLSocketFactory(sslConnSocketFactory)
        .build();

CloseableHttpClient client = HttpClientBuilder.create()
        .setConnectionManager(connectionManager)
        .build();

HttpGet httpGet = new HttpGet("https://mms.nw.ru/");
HttpHost host = RoutingSupport.determineHost(httpGet);
ClassicHttpResponse response = client.executeOpen(host, httpGet, null);
Assertions.assertEquals(200, response.getCode());

But the SSLConnectionSocketFactory class and setSSLSocketFactory method of PoolingHttpClientConnectionManagerBuilder became deprecated.

I have changed the code to

var sslContext = SSLContexts.custom()
        .loadTrustMaterial(null, TrustAllStrategy.INSTANCE)
        .build();

var tlsStrategy = ClientTlsStrategyBuilder.create()
        .setSslContext(sslContext)
        .setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
        .build();

var connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
        .setTlsSocketStrategy((TlsSocketStrategy) tlsStrategy)
        .build();

CloseableHttpClient client = HttpClientBuilder.create()
        .setConnectionManager(connectionManager)
        .build();

HttpGet httpGet = new HttpGet("https://mms.nw.ru/");
HttpHost host = RoutingSupport.determineHost(httpGet);
ClassicHttpResponse response = client.executeOpen(host, httpGet, null);
Assertions.assertEquals(200, response.getCode());

It throws javax.net.ssl.SSLHandshakeException: No name matching mms.nw.ru found cause java.security.cert.CertificateException: No name matching mms.nw.ru found.

What is wrong ?


Solution

  • As of version 5.4 HttpClient makes use of built-in hostname verification provided by JSSE. In order to disable hostname verification completely initialize the TLS strategy in your code the following way

    var tlsStrategy = new DefaultClientTlsStrategy(
      sslContext, 
      HostnameVerificationPolicy.CLIENT, 
      NoopHostnameVerifier.INSTANCE);