Retrieving the Certification Path of an SSL Server - Java Network

Java examples for Network:SSL

Description

Retrieving the Certification Path of an SSL Server

Demo Code

import java.io.IOException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class Main {

  public void main(String[] argv) {
    try {//w  w w . j a  v a 2 s  .  c o m
      // Create the client socket
      int port = 443;
      String hostname = "hostname";
      SSLSocketFactory factory = HttpsURLConnection
          .getDefaultSSLSocketFactory();
      SSLSocket socket = (SSLSocket) factory.createSocket(hostname, port);

      // Connect to the server
      socket.startHandshake();

      // Retrieve the server's certificate chain
      java.security.cert.Certificate[] serverCerts = socket.getSession()
          .getPeerCertificates();

      // Close the socket
      socket.close();
    } catch (SSLPeerUnverifiedException e) {
    } catch (IOException e) {
    }
  }
}

Related Tutorials