11.14. SSL

Problem

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

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>

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 ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.