Using the https protocol with a URLConnection

Ingredients:

My Environment: Software required:

Method:

Example:

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

public class TestHttps {

    // here we're using the https protocol
    String updateSourceURL = "https://www.connect4.com.au/index.html";

    public static void main(String argv[]) throws Exception {

        Properties prop  = new Properties();

        // set the protocol handler
        prop.put("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");

        // my JRE barfs if this is not set
        prop.put("user.timezone","GMT+10:00");

        // I'm using my own certificate store
        // If you have your certificate in one of the standard places (cacerts or
        // jssecacerts) then ignore this line.
        prop.put("javax.net.ssl.trustStore","/home/peterlg/certificates/myjavacerts");

        // use these next two for going through a proxy server
        // prop.put("https.proxyHost","pxysvr.myorg.com");
        // prop.put("https.proxyPort","80"); // or try 443

        // set our properties now
        System.setProperties(prop);

        // we don't need this if we set the .../jre/lib/security/java.security file
        java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        // do the URL thing like normal...
        URL url = new URL(updateSourceURL);
        URLConnection urlConnection = url.openConnection();
        BufferedReader in =
            new BufferedReader(
                new InputStreamReader(urlConnection.getInputStream()));

        String inputLine;
        String text = "";

        while ((inputLine = in.readLine()) != null) {
            text = text + inputLine + "\n";
            }

        System.out.println(text);
}
 

Errors:

Exception in thread "..." javax.net.ssl.SSLException: untrusted server cert chain
This generally indicates that a certificate in the chain of certificates is in some way invalid, i.e. it is bogus, or it has expired. It is somewhat difficult to track down which certificate is causing the problem. I found that trying to use the URL https://www.verisign.com fails with this exception, although root CA certificates for this URL appear to be available in the cacerts file. It is because of this error that I used my own certificate store file.

Unsupported ... SSL ...
...stuff...

Exception in thread "..." java.net.SocketException: SSL implementation not available
    ...
    at java.net.SocketException.(SocketException.java:38)
    at javax.net.ssl.DefaultSSLSocketFactory.createSocket([DashoPro-V1.2-120198])
    ...
    at com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnection.connect([DashoPro-V1.2-120198])
    at com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnection.getInputStream([DashoPro-V1.2-120198])

This may indicate that the URL provided is malformed. No https:? Non-existant URL?