Clientbuilder.sslsocketfactory(sslsocketfactory) not supported on jdk 9+

Explanation of clientbuilder.sslsocketfactory(sslsocketfactory) in JDK 9+

Starting from JDK 9, the method clientbuilder.sslsocketfactory(sslsocketfactory) is not supported anymore. This method was used in previous versions of JDK to set a custom SSL socket factory for the HTTP client builder. An SSL socket factory provides the ability to create SSL sockets for secure communication over HTTPS.

In JDK 9 and later versions, the HttpClient class was introduced as a replacement for the deprecated HttpURLConnection class. The HttpClient class provides more flexible and modern APIs for making HTTP requests and handling responses.

Example: Using HttpClient in JDK 11+


import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class ExampleHttpClient {
    public static void main(String[] args) {
        HttpClient httpClient = HttpClient.newBuilder()
                .build();

        HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(URI.create("https://example.com"))
                .build();

        try {
            HttpResponse response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
            System.out.println("Response code: " + response.statusCode());
            System.out.println("Response body: " + response.body());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  

The example code demonstrates how to use the new HttpClient in JDK 11+ to make a simple HTTPS GET request. We create an instance of HttpClient using the newBuilder() method, and then build a GET request using HttpRequest.newBuilder(). Finally, we send the request using httpClient.send() and handle the response accordingly.

Note that in this new approach, you don’t need to set a custom SSL socket factory explicitly. The HttpClient class handles SSL/TLS configurations automatically based on the system’s trust store and other security settings.

Similar post

Leave a comment