From 3ec16e5541ba29fa4d2117c3c17c7f7c2b2b389d Mon Sep 17 00:00:00 2001 From: Alexandra Wishart Date: Fri, 13 Nov 2015 14:24:00 +0000 Subject: [PATCH] Task 1537: Updated sample code to use TLS 1.2 --- .../src/com/example/RESTRequest.java | 28 ++++++++++++++----- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/java/message-hub-kafka-ssl/src/com/example/RESTRequest.java b/java/message-hub-kafka-ssl/src/com/example/RESTRequest.java index bae9418..8cd49cf 100644 --- a/java/message-hub-kafka-ssl/src/com/example/RESTRequest.java +++ b/java/message-hub-kafka-ssl/src/com/example/RESTRequest.java @@ -25,6 +25,8 @@ import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; public class RESTRequest { @@ -46,7 +48,7 @@ public RESTRequest(String baseUrl, String apiKey) */ public String get(String target, boolean acceptHeader) { - HttpURLConnection connection = null; + HttpsURLConnection connection = null; if(!target.startsWith("/")) { @@ -55,9 +57,13 @@ public String get(String target, boolean acceptHeader) try { - // Create connection to the REST URL. - URL url = new URL(baseUrl + target); - connection = (HttpURLConnection)url.openConnection(); + // Create secure connection to the REST URL. + SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); + sslContext.init(null, null, null); + + URL url = new URL(baseUrl + target); + connection = (HttpsURLConnection)url.openConnection(); + connection.setSSLSocketFactory(sslContext.getSocketFactory()); connection.setRequestMethod("GET"); // Apply API key header and kafka content type Accept header if // the 'acceptHeader' flag is set to true. @@ -110,7 +116,7 @@ public String get(String target, boolean acceptHeader) */ public String post(String target, String body, int[] ignoredErrorCodes) { - HttpURLConnection connection = null; + HttpsURLConnection connection = null; int responseCode = 0; if(!target.startsWith("/")) @@ -120,14 +126,22 @@ public String post(String target, String body, int[] ignoredErrorCodes) try { - // Create connection to the REST URL. + + + // Create secure connection to the REST URL. + SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); + sslContext.init(null, null, null); + URL url = new URL(baseUrl + target); - connection = (HttpURLConnection)url.openConnection(); + connection = (HttpsURLConnection)url.openConnection(); + connection.setSSLSocketFactory(sslContext.getSocketFactory()); connection.setDoOutput(true); connection.setRequestMethod("POST"); + // Apply headers, in this case, the API key and Kafka content type. connection.setRequestProperty("X-Auth-Token", this.apiKey); connection.setRequestProperty("Content-Type", "application/json"); + // Send the request, writing the body data // to the output stream.