Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

11.14. SSL

11.14.1. Problem

You need to execute a method using HTTP over Secure Sockets Layer (SSL).

11.14.2. Solution

If you are working with a server that has a certificate signed by a certificate authority included in the Java Secure Socket Extension (JSSE), HttpClient automatically handles HTTP over SSL; just use a URL that starts with https. The following example retrieves Amazon.com's sign-in page using HTTP over SSL:

               import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
HttpClient client = new HttpClient( );
String url = "https://www.amazon.com/gp/flex/sign-in.html";
HttpMethod method = new GetMethod( url );
client.executeMethod( method );
String response = method.getResponseBodyAsString( );
System.out.println( response );
method.releaseConnection( );
method.recycle( );

This example executes a simple GetMethod constructed with a URL starting with https. The output of this example is:

0    WARN  [main] org.apache.commons.httpclient.HttpMethodBase     - Response 
content length is not known
297  WARN  [main] org.apache.commons.httpclient.HttpMethodBase     - Response 
content length is not known
<html>
<head><title>Amazon.com Sign In</title>
</head>
.......... Content ..................
</html>

11.14.3. Discussion

HttpClient handles SSL automatically, if it can verify the authenticity of a certificate against an authority; this is why this recipe is so similar to Recipe 11.3. The example in this recipe only works if you are dealing with a site that has a certificate signed by a well-known authority. The Java Runtime Environment (JRE) keeps track of the signatures of all the known certificate authorities in a file named cacerts. cacerts can be found in /usr/java/latest/jre/lib/security/cacerts; it is an archive that has a default password of changeit. For a list of certificate authorities in Java, execute the following command line and supply the default password:

keytool -list -keystore C:\j2sdk1.4.2_04\jre\lib\security\cacerts

The list will contain certificate fingerprints for Thawte, Entrust, Verisign, and other commercial certificate authorities. If you wish to use the JSSE without having to write your own ProtocolSocketFactory, you need to obtain a certificate signed by an authority.

11.14.4. See Also

If you need to work with a self-signed certificate, see the next recipe.


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.