Category Archives: networks

How to ignore SSL certificate errors in Apache HttpClient 4.4

HttpClient has long been popular for implementing outbound HTTP clients, remoting & services in Java. Release 4.4 brings a much-improved Builder- style API for configuration, but with some loss of backwards compatibility.

For developers using HTTPS clients, one in-house desire is questionable but common: testing HTTPS connectivity, without an individual certificates for their local appserver.

Security issues aside, this was commonly done in earlier versions of HttpClient — but the configuration API (and SSL especially) is radically changed in 4.4.

Here’s how you can accomplish this:

public HttpClient createHttpClient() {
	HttpClientBuilder b = HttpClientBuilder.create();

	// setup a Trust Strategy that allows all certificates.
	//
	SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
		public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
			return true;
		}
	}).build();
	b.setSslcontext( sslContext);

	// don't check Hostnames, either.
	// 		-- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
	HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

	// here's the special part:
	// 		-- need to create an SSL Socket Factory, to use our weakened "trust strategy";
	//		-- and create a Registry, to register it.
	//
	SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
	Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
			.register("http", PlainConnectionSocketFactory.getSocketFactory())
			.register("https", sslSocketFactory)
			.build();

	// now, we create connection-manager using our Registry.
	// 		-- allows multi-threaded use
	PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
	b.setConnectionManager( connMgr);

	// finally, build the HttpClient;
	//		-- done!
	HttpClient client = b.build();
	return client;
}

This is extracted from an actual working implementation. Other answers for earlier HttpClient versions are popular, but just don’t work at 4.4.

I spent hours exhausting multiple possibilities, to get this to work — enjoy! See the original answer on StackOverflow.