How to Implement HTTPS Server Authentication with Oracle JDK

1) Create the HttpsServerAuthenticationSample.java file:

import java.net.HttpURLConnection;
import java.net.URL;

import static java.lang.System.out;
import static java.lang.System.setProperty;

public final class HttpsServerAuthenticationSample {

  public static void main(final String[] args) throws Exception {
    final URL url = new URL("https://localhost/"); // default port is 443

    final SSLContext ctx = SSLContext.getInstance("TLS");

    ctx.init(null, new TrustManager[] { new X509TrustManager() {

        public void checkClientTrusted(final X509Certificate chain[], final String authType) {
        }

        public void checkServerTrusted(final X509Certificate chain[], final String authType) {
        }

        public X509Certificate[] getAcceptedIssuers() {
          return new X509Certificate[] {};
        }

      }

    }, null); // null trust manager

    HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

    final HttpURLConnection conn = (HttpURLConnection)url.openConnection();

    conn.connect();

    out.println(conn.getResponseCode() + " - " + conn.getResponseMessage());
  }

  private HttpsServerAuthenticationSample() {
  }

}

2) Compile the HttpsServerAuthenticationSample.java file.

3) Launch the HttpsServerAuthenticationSample class.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s