The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.net.ssl  [4 examples]

e499. Creating an SSL Client Socket

When an SSL client socket connects to an SSL server, it receives a certificate of authentication from the server. The client socket then validates the certificate against a set of certificates in its \meta{trust store}.

The default truststore is <java-home>/lib/security/cacerts. If the server's certificate cannot be validated with the certificates in the truststore, the server's certificate must be added to the truststore before the connection can be established.

    try {
        int port = 443;
        String hostname = "hostname";
        SocketFactory socketFactory = SSLSocketFactory.getDefault();
        Socket socket = socketFactory.createSocket(hostname, port);
    
        // Create streams to securely send and receive data to the server
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
    
        // Read from in and write to out...
    
        // Close the socket
        in.close();
        out.close();
    } catch(IOException e) {
    }

A different truststore can be specified using the javax.net.ssl.trustStore system property. (If you are trying to set up an SSL client and server for testing purposes, you can set the truststore to the keystore that was created in e500 Creating an SSL Server Socket.)

    > java -Djavax.net.ssl.trustStore=truststore -Djavax.net.ssl.trustStorePassword=123456 MyApp

 Related Examples
e500. Creating an SSL Server Socket
e501. Retrieving the Certification Path of an SSL Server
e502. Disabling Certificate Validation in an HTTPS Connection


© 2002 Addison-Wesley.