Alexdharma
Alexdharma

Reputation: 55

HttpClient set up SSLHostnameVerifier and ConnectionManager at the same time

Registry<ConnectionSocketFactory> reg =RegistryBuilder<ConnectionSocketFactory>create().register("https", new  
SSLConnectionSocketFactory(ctx)).register("http", new PlainConnectionSocketFactory())
            .build();

    PoolingHttpClientConnectionManager cm = newPoolingHttpClientConnectionManager(reg);

    client = HttpClients.custom()
            .setConnectionManager(cm)
            .setDefaultRequestConfig(config)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .build();

I use NoopHostnameVerifier because I do not want to verify SSL, but in my ConnectionManager exists essential logic and have not chances forgot ConnectionManager.

The problem is that if I have ConnectionManager and SSLHostnameVerifier(NoopHostnameVerifier), I get the following error:

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

What might be causing this problem?

Upvotes: 0

Views: 2822

Answers (2)

Hunsu
Hunsu

Reputation: 3391

Here is what worked for me. I found it here.

PoolingHttpClientConnectionManager cm;
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            clientBuilder.setSslcontext(sslContext);
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();
            cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
            cm = new PoolingHttpClientConnectionManager();
        }

Upvotes: 1

Victory
Victory

Reputation: 5890

You need to use the singleton of NoopHostnameVerifier

So change new NoopHostnameVerifier() to NoopHostnameVerifier.INSTANCE

Upvotes: 0

Related Questions