Skip to content

Instantly share code, notes, and snippets.

@jctoledo
Last active December 19, 2015 02:09
Show Gist options
  • Save jctoledo/5881157 to your computer and use it in GitHub Desktop.
Save jctoledo/5881157 to your computer and use it in GitHub Desktop.
// For testing reasons one can add a X509TrustManager to a HttpClient to avoid the SSLPeerUnverifiedException
// References:
// http://javaskeleton.blogspot.com/2010/07/avoiding-peer-not-authenticated-with.html
// http://en.wikibooks.org/wiki/Programming:WebObjects/Web_Services/How_to_Trust_Any_SSL_Certificate
// Made some customizations to these guides. Works with Java 7 (no NullPointerException when calling init() of SSLContext) and does not use any deprecated functions of HttpClient, SSLContext...
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
private DefaultHttpClient getSecuredHttpClient(HttpClient httpClient) throws Exception {
final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return _AcceptedIssuers;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
};
ctx.init(null, new TrustManager[] { tm }, new SecureRandom());
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
return new DefaultHttpClient(ccm, httpClient.getParams());
} catch (Exception e) {
throw e;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment