Sunday, July 1, 2012

Apache HTTP Client - Ignore SSL Problems

Sometimes, especially when testing, it can be useful to make Apache HTTP Client ignore the SSL problems.
SSL problems may include ignoring of certificate trust (issuers) and host verification. The following snippet creates an Apache HttpClient with SingleClientConnManager that will ignore the SSL problems:
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;

public HttpClient createHttpClient() {
  TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

    public[] getAcceptedIssuers() {
     return null;

    public void checkClientTrusted([] certs, String authType) {

    public void checkServerTrusted([] certs, String authType) {
  } };
  SSLContext context = SSLContext.getInstance("TLS");
  context.init(null, trustAllCerts, null);

  SSLSocketFactory sf = new SSLSocketFactory(context, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

  SchemeRegistry schemeRegistry = new SchemeRegistry();
  schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
  schemeRegistry.register(new Scheme("https", 443, sf));

  SingleClientConnManager cm = new SingleClientConnManager(schemeRegistry);

  return new DefaultHttpClient(cm);

Pay Attention! In production you must use a valid SSL! Use this code for testing purposes only!