/* Basic TLS Client Testing Tool
 * Luke H 2025 0.1
 *
 * Update the following paramaters and then compile the code.
 * httpsUrl
 * tlsVersion
 *
 * Recommend that this be run using SSL Debugging Flags at runtime. Choose one of the sample options below.
 *
 * -Djavax.net.debug=ssl,handshake
 * -Djavax.net.debug=all
 */

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.security.KeyManagementException;

public class TLSClient {

    public static void main(String[] args) {
        String httpsUrl = "https://your-api-endpoint.com"; // Replace with actual URL
        String tlsVersion = "TLSv1.3"; // Change to "TLSv1.2" to test that version

        try {
            // Set up SSL context for specified TLS version
            SSLContext sslContext = SSLContext.getInstance(tlsVersion);
            sslContext.init(null, null, null);
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            // Open connection
            URL url = new URL(httpsUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(sslSocketFactory);

            // Optional: set method and headers
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent", "Java TLS Client");

            // Read and print the response
            int responseCode = conn.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine).append("\n");
            }
            in.close();

            System.out.println("Response Body:\n" + response);

        } catch (NoSuchAlgorithmException e) {
            System.err.println("TLS version not supported: " + e.getMessage());
        } catch (KeyManagementException e) {
            System.err.println("Error initializing SSL context: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("Connection error: " + e.getMessage());
        }
    }
}
