Main Contents

Java SSL/HTTPS via JSSE: Write once, run everywhere?

November 4, 2008

A common Java problem is to connect to an authenticated Web Service via HTTPS. Doing so while preserving portability can be tricky.

There are a lot of helpful tutorials out on the web that say to do something like this:

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
    final MyAuthenticator auth = new MyAuthenticator(username, password);
    Authenticator.setDefault(auth);
    try {
      final URL url = new URL(httpsurl);
      try {
        final HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        try {
          // Rest of code

However, if you try to deploy the code on a system using IBM’s JVM, you’ll get a rude surprise:

Exception in thread "main" java.lang.NoClassDefFoundError: com.sun.net.ssl.internal.ssl.Provider
        at java.lang.J9VMInternals.verifyImpl(Native Method)
        at java.lang.J9VMInternals.verify(J9VMInternals.java:72)
        at java.lang.J9VMInternals.initialize(J9VMInternals.java:134)
        [...]

In fact, the addProvider and setProperty stuff is completely unnecessary. You can simply do:

final MyAuthenticator auth = new MyAuthenticator(username, password);
    Authenticator.setDefault(auth);
    try {
      final URL url = new URL(httpsurl);
      try {
        final HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection();
        try {
          // Rest of code

The key detail is emphasized in bold above. The class to use is javax.net.ssl.HttpsURLConnection, rather than the com.sun.* class Eclipse may offer you. Your code will then run on IBM JVMs as well as the Sun JVM and OpenJDK.

Of course, if you’re getting the exception from someone else’s code, you might need to get them to fix it. Because of the prevalence of incorrect examples, it’s quite common to find the error in frameworks and libraries.

Filed under: Java | Comments (0)

Leave a comment

Login