Tuesday, March 1, 2016

REST Client


SIMPLE REST CLIENT



 package com.bmc.rest;  
 import java.io.BufferedInputStream;  
 import java.io.BufferedReader;  
 import java.io.IOException;  
 import java.io.InputStreamReader;  
 import java.io.Reader;  
 import java.net.HttpURLConnection;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 public class Client {  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           try {  
                GETclient();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
      public static void GETclient() throws IOException {  
           // creating a URL object  
//Your REST Web URL
           URL url = new URL(  
                     "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98");  
           // creating connection object  
           HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
           // setting the connection as GET it can be POST/ PUT / DELETE etc  
           conn.setRequestMethod("GET");  
           // I am accepting the media type as JSON you can do XML .  
           conn.setRequestProperty("Accept", "application/json");  
           // If the response has no error read the response  
           if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {  
                System.out.println(conn.getResponseCode());  
           }  
           BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());  
           while (bis.available() > 0) {  
                System.out.print((char) bis.read());  
           }  
           conn.disconnect();  
      }  
 }  

No comments:

Post a Comment