Consuming REST API through JAVA

REST APIs are very popular nowadays and it's being used widely across various platforms and technologies . Whoever working on REST API's or want to access the services either they have to Consume the services or expose the services.

I'm taking one simple example of consuming REST URL through Java code. Please follow code snippet shown below

package practice.java.workspace;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.simple.parser.*;
import org.json.simple.parser.JSONParser;
public class NetClientGet {
    public static void main(String[] args) {
       // NetClientGet netClientGet = new NetClientGet();
                   try {
                   System.out.println("hi");
                   JSONParser parser = new JSONParser();
        URL url = new URL("http://dummy.restapiexample.com/api/v1/employees");//your url i.e fetch data from .
                   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                   conn.setRequestMethod("GET");
                   conn.setRequestProperty("Accept", "application/json");
                   System.out.println("hi json");
                   if (conn.getResponseCode() != 200) {
                       throw new RuntimeException("Failed : HTTP Error code : "
                               + conn.getResponseCode());
                   }
                   InputStreamReader in = new InputStreamReader(conn.getInputStream());
                   BufferedReader br = new BufferedReader(in);
                   String output;
                   while ((output = br.readLine()) != null) {
                       Object obj = parser.parse(output);
                    //JSONArray array = (JSONArray)obj;
                       System.out.println(output);
                     
                   }
       
                   conn.disconnect();

               } catch (Exception e) {
                   System.out.println("Exception in NetClientGet:- " + e);
               }
    }
}


The output of the above code 


Comments

Popular posts from this blog

Sample HZ API's script to Create Contacts and Contact Points in Oracle

REST integration built-in OIC to read Large files with size more than 10MB