Saturday, September 17, 2016

Simple Java Program to Invoke an OAuth webservice

OAuth is an authentication mechanism that allows an application to connect to a service on behalf of a user without sharing their password. There are several webservices exposed by third parties, which mandates client to use OAuth mechanism to connect with their service.

In OAuth mechanism, we need to pass an authentication token to the webservice, instead of username/password while invoking their service.

Below is a sample standalone Java program, which will connect to a webservice using OAuth mechanism.
 

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

public class InvokeSampleService {

 public static void main(String[] args) {

  String authToken="trtry65ttfdfsfdsfdcxxewd";
  String messagetobeSent="{\"id\":\"10001\",\"name\":\"prabs\",\"totalmark\":\"79\"}";
  try {
   URL url = new URL("https://api.myservice.com/student/update");
   HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
   conn.setDoOutput(true);
   conn.setRequestMethod("POST");
   conn.setRequestProperty("Content-Type", "application/json");
   conn.setRequestProperty("Authorization","Bearer "+authToken);

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

   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 above program will invoke student update API to update the total mark of a student.

This API used OAuth based authentication. So, as you can see in the code, the authentication token is passed to this API  using setRequestProperty() method of HTTPsURLConnection class. The auth token should be passed in the below format as mentioned in the above program.

conn.setRequestProperty("Authorization","Bearer "+authToken);

 

No comments:

Post a Comment