Yang Hanlin
Yang Hanlin

Reputation: 566

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

Upvotes: 14

Views: 16511

Answers (2)

ok2c
ok2c

Reputation: 27528

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.

Upvotes: 30

Travis Schneeberger
Travis Schneeberger

Reputation: 2080

The following is a solution that avoids deprecated code.

CloseableHttpClient httpclient = HttpClients.custom()
                .setConnectionManager(
                    PoolingHttpClientConnectionManagerBuilder.create()
                        .setTlsSocketStrategy(
                            DefaultClientTlsStrategy(
                                SSLContextBuilder.create()
                                    .loadTrustMaterial(TrustAllStrategy.INSTANCE)
                                    .build(),
                                HostnameVerificationPolicy.BOTH,
                                NoopHostnameVerifier.INSTANCE
                            )
                        )
                        .build()
                )
                .build();

Upvotes: 3

Related Questions