Provide a custom SSLProtocolSocketFactory that is configured to trust your self-signed certificate.
A sample implementation of SSLProtocolSocketFactory named EasySSLProtocolSocketFactory is available via
HttpClient's CVS repository, and the following example uses it to trust
a self-signed certificate:
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.protocol.Protocol;
HttpClient client = new HttpClient( );
String url = "https://pericles.symbiont.net/jccook";
ProtocolSocketFactory socketFactory =
new EasySSLProtocolSocketFactory( );
Protocol https = new Protocol( "https", socketFactory, 443);
Protocol.registerProtocol( "https", https );
HttpMethod method = new GetMethod( url );
client.executeMethod( method );
String response = method.getResponseBodyAsString( );
System.out.println( response );
method.releaseConnection( );
method.recycle( );This executes and accepts the self-signed certificate from
pericles.symbiont.net:
Word up, this page was served using SSL!
EasySSLProtocolSocketFactory
and EasyX509TrustManager can be
obtained from HttpClient's CVS in the src/contrib directory. If you do not want to
checkout the source code from CVS, you can also obtain these two classes
from ViewCVS on cvs.apache.org.
HttpClient's CVS repository can be accessed at http://cvs.apache.org/viewcvs.cgi/jakarta-commons/httpclient/,
and the two classes are in the src/contrib/org/apache/commons/httpclient/contrib/ssl
directory. To use these classes, you must integrate them into your own
project, customizing the behavior of these classes as you see
fit.
EasySSLProtocolSocketFactory
uses the EasyX509TrustManager to
validate a certificate. To customize the criteria for certificate
acceptance and alter the implementation of EasyX509TrustManager. For example, if you only
want to accept a certificate from a specific hostname, change the
implementation of the isServerTrusted() method in EasyX509TrustManager.
In the same package as EasySSLProtocolSocketFactory and EasyX509TrustManager is an implementation of
SSLProtocolSocketFactory named
StrictSSLProtocolSocketFactory, which
makes sure that the hostname of the SSL server matches the hostname of
the SSL certificate. For more information, go to HttpClient's CVS
repository (http://cvs.apache.org/viewcvs.cgi/jakarta-commons/httpclient/)
and download StrictSSLProtocolSocketFactory from this
src/contrib/org/apache/commons/httpclient/contrib/ssl
directory.
