[ Back | Previous | Next ]

How to access a URL with https://?

Package:
java.net.*
Product:
JDK
Release:
1.2
Related Links:
General
URLConnection
URLDecoder
Comment:
The technique for using JDK 1.2-compatible VMs relies primarily on the Java Secure
Sockets Extension (JSSE) 1.0.1. Before that technique will work, you must install the
JSSE and add it to the class path of the client VM in question. 

After you have installed the JSSE, you must set a system property and add a new
security provider to the Security class object. There are a variety of ways to do both of
these things, but for the purposes of this article, the programmatic method is shown: 

 System.setProperty("java.protocol.handler.pkgs",
      "com.sun.net.ssl.internal.www.protocol");
 Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

After making the previous two method calls, the MalformedURLException will no longer
be thrown by calling the following code: 

 URL url = new URL("https://[your server]");

If you are connecting to the standard SSL port, 443, you have the option of appending the
port number to the URL string. However, if your Web server is using a nonstandard port
for SSL traffic, you'll need to append the port number to your URL string like this: 

 URL url = new URL("https://[your server]:7002");

One caveat of that technique concerns a URL that refers to a server that has an
unsigned or invalid SSL certificate. In that case an attempt to retrieve the input or output
stream from the URL's connection object will throw an SSLException with the message
"untrusted server cert chain." If the server has a valid, signed certificate, no exception will
be thrown. 

 URL url = new URL("https://[your server]");
 URLConnection con = URL.openConnection();
 //SSLException thrown here if server certificate is invalid
 con.getInputStream();
 

The obvious solution to that problem is to get signed certificates for your server.
However, a workaround to that has been proposed on the Java Developer Connection
forums and can be found at the following URL:
http://forum.java.sun.com/forum?14@@.787ad8de.