How do I bypass certificate verification errors with Apache HttpComponents HttpClient 5.1?
I've found a working solution to bypass such errors in HttpClient 4.5 that suggests customizing HttpClient instance:
HttpClient httpClient = HttpClients
.custom()
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
But it is not applicable to HttpClient 5.1, as setSSLContext and setSSLHostnameVerifier methods do not exist in HttpClientBuilder (which HttpClients.custom() returns).
There are several specialized builders in HC 5.1 that can be used to do the same:
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(SSLConnectionSocketFactoryBuilder.create()
.setSslContext(SSLContextBuilder.create()
.loadTrustMaterial(TrustAllStrategy.INSTANCE)
.build())
.setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build())
.build())
.build();
UPDATE: For HC version 5.4 please see Travis Schneeberger answer.
The following is a solution that avoids deprecated code.
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(
PoolingHttpClientConnectionManagerBuilder.create()
.setTlsSocketStrategy(
new DefaultClientTlsStrategy(
SSLContextBuilder.create()
.loadTrustMaterial(TrustAllStrategy.INSTANCE)
.build(),
HostnameVerificationPolicy.BOTH,
NoopHostnameVerifier.INSTANCE
)
)
.build()
)
.build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With