Java TLSv1.3 protocol code example using SSLSocket

Java-TLSv1.3 Example

✌️Oracle Java added support to TLS v1.3 in 8u261-b12 update!

Java has support to TLSv1.3 protocol for Java JDK 1.8 and well supported by JDK 11 and later, this example demonstrates how you can connect to server (http address) using SSLSocket using TLSv1.3 protocol and TLS_AES_128_GCM_SHA256 cipher.


 * Example of TLSv1.3 connection
 * This code should work with
 * Java JDK 8 11, 15
 * Note: Make sure you are using
 * the the JDK version that
 * Supports TLSv1.3
public class TSLv1_3Example {

    private static final String host="";
    private static final int port=443;
    private static final String TLSV1_3 = "TLSv1.3";
    private static final String TLS_AES_128_GCM_SHA256 = "TLS_AES_128_GCM_SHA256";
    private static SSLSocket sslSocket;

    public static void main(String... args) throws Exception {



    public static void getSslSocket() throws IOException {

        SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, port);
        //Setting the TSLv1.3 protocol
        sslSocket.setEnabledProtocols(new String[]{TLSV1_3});
        //Setting the Cipher: TLS_AES_128_GCM_SHA256
        sslSocket.setEnabledCipherSuites(new String[]{TLS_AES_128_GCM_SHA256});


     * Read the sslSocket response
    public static void readResponse() {

        try(BufferedReader in = new BufferedReader(
                new InputStreamReader(
                        sslSocket.getInputStream()))) {

            String responseData;
            while ((responseData = in.readLine()) != null)

        } catch (IOException e) {
            System.out.println("Error occurred while reading Socket Response...");

     * Send Request to sslSocket
     * @throws IOException
    public static void sendRequest() throws IOException {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(sslSocket.getOutputStream());
        PrintWriter printWriter = new PrintWriter(new BufferedWriter(outputStreamWriter));
        printWriter.println("GET /test-url HTTP/1.1\r\n");
HTTP/1.1 200 OK
Date: Tue, 13 Apr 2021 05:43:25 GMT
Content-Type: text/html
Content-Length: 267
Connection: close
Try Out Code2care Dev Tools:


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.