Saturday, September 17, 2016

Java program to invoke a service requiring basic authentication

Most of the web applications/webservices available in the internet uses some kind of authentication mechanism to avoid unauthorized access. One of the simplest authentication mechanim used is the base64 based authentication where the client has to send the user name and password information to the webservice/web application in an encrypted format.

Given below is a simple Java program which uses basic authentication mechanism to connect to the webservice and retrieve the student information.


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class InvokeSampleService {

 public static void main(String[] args) {

  String authString = "my_username:my_password";
  byte[] authEncBytes = org.apache.commons.codec.binary.Base64.encodeBase64(authString.getBytes());
  String authStringEnc = new String(authEncBytes);
  try {
  
   URL url = new URL("https://api.myservice.com/student/retrieve");
   HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
   conn.setDoOutput(true);
   conn.setRequestMethod("GET");
   conn.setRequestProperty("Authorization","Basic "+authStringEnc); 
  
   if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
    throw new RuntimeException("Failed : HTTP error code : "
      + conn.getResponseCode());
   }
   BufferedReader br = new BufferedReader(new InputStreamReader(
     (conn.getInputStream())));
   String output;
   System.out.println("Output from Server ....:");
   while ((output = br.readLine()) != null) {
    System.out.println(output);
   }
   conn.disconnect();
  } catch (Exception ex) {
   ex.printStackTrace();
  }
 }
}



The my_username and my_password texts mentioned in authString assignment should be replaced with the username & password that you received from the webservice/application provider.

No comments:

Post a Comment