Disabling SSL checks with Apache HttpClient 4.3.x
In some contexts, it might very useful to disable the SSL checks when connecting to https
using Java. In my case, I was creating a temporary test server using Docker, where the proxy in front of my application was an Nginx with a self signed certificate.
Of course, when connecting with Java, this call is rejected because:
- the certificate chain is invalid
- the host name cannot be trusted
But the truth is: in this very context, I do not care.
Disclaimer: of course such checks MUST be enabled against a production-like environment or external system.
Using Apache HttpClient 4.x, disabling SSL checks is actually quite easy:
SSLConnectionSocketFactory sslSocketFactory;
if (disableSsl) {
SSLContext ctx;
try {
X509TrustManager x509TrustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[]{x509TrustManager}, new SecureRandom());
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new OTHttpClientSSLSetupException(e);
}
sslSocketFactory = new SSLConnectionSocketFactory(
ctx,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
);
} else {
sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
}
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
HttpClient client = HttpClientBuilder.create()
.setConnectionManager(new PoolingHttpClientConnectionManager(registry))
.build();
That's it. I fall back to the defaults when I do not want to disable the SSL checks.