How to send JSON data post to a REST Web Service using Java TLS with Authorization Header

With the increasing popularity of JSON data as transport medium and REST Web Services being used for system to system integration this a very basic requirement these days.

Source for WebServiceHandler.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

import com.ebusiness.objects.JsonResponse;


public class WebServiceHandler {

 public WebServiceHandler() {
 }

 public JsonResponse makeServiceCall(String url, String username, String password,
   String jsonString) {

  JsonResponse jsonResponse = new JsonResponse();

  try{ 

   SSLContext sc = SSLContext.getInstance("TLSv1.2"); 
   sc.init(null, null, new java.security.SecureRandom());

   URL myUrl = new URL(url);
   HttpsURLConnection conn = (HttpsURLConnection) myUrl.openConnection();
   conn.setSSLSocketFactory(sc.getSocketFactory());
   conn.setDoOutput(true);
   conn.setReadTimeout(30000);
   conn.setConnectTimeout(30000);
   conn.setUseCaches(false);
   conn.setAllowUserInteraction(false);
   conn.setRequestMethod("POST");
   conn.setRequestProperty("Content-Type", "application/json");
   conn.setRequestProperty("Accept-Charset", "UTF-8");

   String userCredentials = username.trim() + ":" + password.trim();
   String basicAuth = "Basic " + new String(Base64.encodeBytes(userCredentials.getBytes()));
   conn.setRequestProperty ("Authorization", basicAuth);

   OutputStream os = conn.getOutputStream();
   os.write(jsonString.getBytes());
   os.flush(); 
   os.close();

   InputStreamReader isr = conn.getResponseCode() == HttpsURLConnection.HTTP_OK  ? new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8) : new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8);
   BufferedReader reader = new BufferedReader(isr);
   String line;
   String resultLine = "";
   while((line = reader.readLine()) != null) {
    resultLine = resultLine + line;
   }
   reader.close();
   jsonResponse.setSuccess(true);
   jsonResponse.setResponseData(resultLine);

  } catch (Exception ex) {
   ex.printStackTrace();
  } 

  return jsonResponse;

 }

}

Source for JsonResponse.java

public class JsonResponse {
 
 private boolean success = false;
 private String responseData = "";
 
 public boolean isSuccess() {
  return success;
 }
 public void setSuccess(boolean success) {
  this.success = success;
 }
 public String getResponseData() {
  return responseData;
 }
 public void setResponseData(String responseData) {
  this.responseData = responseData;
 }
 

}

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.