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>
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
${JAVA_HOME}/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_04jrelibsecuritycacerts
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.
3.142.173.238