The HTTPS Protocol Handler

SSL is often used as the underlying communication protocol of HTTPS. If you’re talking to an HTTPS server you can write the SSL-level code yourself, but it’s generally easier to use the standard URL class to talk to the server and install a protocol handler that implements the HTTPS protocol. JSSE comes with such a protocol handler.

As an example, here’s a simple URL-based client that can retrieve arbitrary URLs:

package javasec.samples.ch14;

import java.io.*;
import java.net.*;

public class URLClient {
    public static void main(String[] args) throws Exception {
        URL u = new URL(args[0]);
        URLConnection uc = u.openConnection(  );
        BufferedReader br = new BufferedReader(
                   new InputStreamReader(uc.getInputStream(  )));
        String s = br.readLine(  );
        while (s != null) {
            System.out.println(s);
            s = br.readLine(  );
        }
    }
}

You can run this code with an HTTP-based URL as follows:

piccolo% java javasec.samples.ch14.URLClient http://www.sun.com/
... lots of output from sun.com ...

Similarly, by specifying the appropriate property for the HTTPS protocol handler, you can connect to an HTTPS-based URL:

piccolo% java \
               -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol \
               javasec.samples.ch14.URLClient https://www.sun.com/

As always, the server (sun.com in this case) will present its certificate to the client, which must verify it using its truststore. In this case, we’ve used the default truststore ($JREHOME/lib/security/cacerts), which contains the root certificate ...

Get Java Security, 2nd Edition 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.