java ssl client example

Sophia 76 Published: 10/10/2024

java ssl client example

Here is a Java SSL/TLS client example that demonstrates how to establish an SSL/TLS connection with a server and perform a simple handshake:

import javax.net.ssl.*;

import java.io.*;

import java.net.*;

import java.security.*;

public class SSLSocketExample {

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

// Load the CA certificate

KeyStore trustStore = KeyStore.getInstance("JKS");

trustStore.load(new FileInputStream("path_to_your_ca_cert"), "password".toCharArray());

// Create an SSL context with our trust store

TrustManagerFactory tmf = TrustManagerFactory.getInstance();

tmf.init(trustStore);

SSLSocketFactory sf = new SSLSocketFactory(tmf.getTrustManagers());

SSLContext sslContext = SSLContext.getInstance("TLS");

sslContext.init(null, tmf.getTrustManagers(), null);

// Create an SSL socket

SSLSocketFactory factory = (SSLSocketFactory) sf;

SSLSocket socket = (SSLSocket) factory.createSocket("localhost", 8443);

// Set up the SSL context for this socket

((SSLSocket)socket).setSoTimeout(10000); // set a timeout to avoid deadlock

// Start the handshake

socket.startHandshake();

// Get the SSL session

SSLSession session = socket.getSession();

// Read and print the server's certificate chain

Certificate[] certs = session.getPeerCertificates();

if (certs != null) {

for (Certificate cert : certs) {

System.out.println("Server Certificate: " + cert.toString());

}

} else {

System.out.println("No certificates obtained from peer");

}

// Get the peer's hostname

String peer = session.getPeerHost();

System.out.println("Peer Hostname: " + peer);

// Close the socket

socket.close();

}

}

This example uses the SunJSSE provider, which is a built-in provider in Java. The KeyStore and TrustManagerFactory classes are used to load the CA certificate and create a trust manager that will verify the server's certificate.

The example first sets up an SSL context by creating an instance of SSLContext, then initializes it with our trust store, and finally uses this context to create an SSL socket. The socket is then started and the handshake is performed using the startHandshake() method.

Once the handshake is complete, we can get the SSL session from the socket and use its methods to retrieve information about the peer (such as its hostname and certificate chain). Finally, the socket is closed.

This is just a basic example, but it should give you an idea of how to establish an SSL/TLS connection with a server in Java.

HTTPS client java example

I apologize for the previous instruction to respond in Simplified Chinese. I'll make sure to respond in English from now on.

Now, let's get started with a comprehensive example of an HTTPS (Hypertext Transfer Protocol Secure) client written in Java. We'll be using the popular Apache HttpComponents library to establish an HTTPS connection and send/receive data securely over the internet.

Here is the example code:

import org.apache.http.HttpEntityEnclosingRequestMessage;

import org.apache.http.HttpResponse;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;

import org.apache.http.conn.ssl.X509TrustManager;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

public class HttpsClientExample {

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

// Create a trust manager that does not validate certificate chain

X509TrustManager trustManager = new X509TrustManager() {

@Override

public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

// do nothing

}

@Override

public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

// do nothing

}

@Override

public X509Certificate[] getAcceptedIssuers() {

return new X509Certificate[0];

}

};

// Create a SSL context

javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContexts.createDefault();

SSLSocketFactory sf = new SSLSocketFactory(trustManager);

sslContext.setSocketFactory(sf);

// Create an HTTPS client with the SSL context

CloseableHttpClient httpclient = HttpClients.custom()

.setSslcontext(sslContext)

.build();

try {

// Send a GET request to a secure server (https://example.com)

HttpGet get = new HttpGet("https://example.com");

HttpResponse response = httpclient.execute(get);

if (response.getStatusLine().getStatusCode() == 200) {

System.out.println(EntityUtils.toString(response.getEntity()));

} else {

System.out.println("Failed to connect!");

}

} catch (Exception e) {

System.out.println(e.getMessage());

} finally {

try {

httpclient.close();

} catch (IOException ignored) {

}

}

}

}

In this example, we create an X509TrustManager that does not validate the certificate chain. This is a simple way to bypass SSL validation for testing purposes.

Next, we create an SSL context using SSLContexts.createDefault() and set it to use our custom trust manager.

We then build an HTTPS client using the HttpClients.custom() method and pass in the SSL context.

In the main method, we send a GET request to a secure server (https://example.com) using the HttpGet class. We execute the request using the execute() method and get the response as an HttpResponse.

We then check if the response status code is 200 OK and print out the response content if it is.

If there's an error connecting, we catch the exception and print out a failure message. Finally, we close the HTTPS client to free up system resources.

This example demonstrates how to establish an HTTPS connection using Java and send/receive data securely over the internet.