Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore SSL certificate errors in Apache HttpComponents HttpClient 5.1

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

like image 251
Yang Hanlin Avatar asked Dec 11 '25 20:12

Yang Hanlin


2 Answers

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.

like image 100
ok2c Avatar answered Dec 13 '25 10:12

ok2c


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();
like image 38
Travis Schneeberger Avatar answered Dec 13 '25 09:12

Travis Schneeberger



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!