Showing posts with label REST. Show all posts
Showing posts with label REST. Show all posts

Monday, April 11, 2016

JAX - RS / Jersey application development and Testing

JAX - RS / Jersey application development and Testing


WEB.XML example


<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
     see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.sudas.study.glassfish.StudyProject.examples</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
</web-app>

This is a car model/ POJO class which is used for returning car objects as list in REST @GET method

package com.sudas.study.glassfish.StudyProject.examples;

public class CarModel {
 public CarModel() {
  // TODO Auto-generated constructor stub
 }
 String brand;
 String model;
 String colour;
 public CarModel(String brand, String model, String colour) {
  super();
  this.brand = brand;
  this.model = model;
  this.colour = colour;
 }
 
 public void setBrand(String brand) {
  this.brand = brand;
 }

 public void setModel(String model) {
  this.model = model;
 }

 public void setColour(String colour) {
  this.colour = colour;
 }

 public String getBrand() {
  return brand;
 }
 public String getModel() {
  return model;
 }
 public String getColour() {
  return colour;
 }
 

}


  • Example of a simple @GET method which produces JSON content



package com.sudas.study.glassfish.StudyProject.examples;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/cars")
public class JaxRSexample1 {

 static List<CarModel> cars = new ArrayList<>();

 // add few cars
 public static void addCars() {
  cars.add(new CarModel("BMW", "x1", "black"));
  cars.add(new CarModel("BMW", "x2", "black"));
  cars.add(new CarModel("BMW", "x3", "black"));

 }

 /***
  * A simple get example which uses content type as application/ JSON in
  * header
  * 
  * @return
  */

 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public static List<CarModel> getJSONexample() {
  addCars();
  return cars;
 }

}

As you can see in the above xml the resource URL is formed upto /webapi, any url-pattern called after the /webapi will result in execution of any rest methods. In the above example the class JaxRSExample1 has a @Path annotation with url-pattern cars. so when ever the url-pattern cars is put after the resource url which is http://localhost:9090/StudyProject/webapi/cars will result in calling the getJSONexample method. 

  • Testing the getJSONexample method using postman

  • Testing the getJSONexample method using custom client


package com.sudas.study.glassfish.StudyProject.examples;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class Example1Client {
 public static void main(String[] args) {
  testClient();
 }

 public static void testClient() {

  HttpURLConnection conn = null;
  try {
   URL url = new URL("http://localhost:9090/StudyProject/webapi/cars");
   // creating connection object
   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());
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  conn.disconnect();
 }
}

OUTPUT:

[{"brand":"BMW","colour":"black","model":"x1"},{"brand":"BMW","colour":"black","model":"x2"},{"brand":"BMW","colour":"black","model":"x3"}]

  • Example of a simple @POST using @FormParam method which produces media type as plain text and consumes media type as x-www-form-urlencoded



package com.sudas.study.glassfish.StudyProject.examples;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/cars2")
public class JaxRSexample2 {

 // a post method which uses @FormParam
 @POST
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 @Produces(MediaType.TEXT_PLAIN)
 public static String postMethod(@FormParam("userName") String userName, @FormParam(" ") String password) 
 {
  return "You have successfully logged in as " + userName;
 }

}

  • Testing the method using postman

  • Testing the method using custom client

package com.sudas.study.glassfish.StudyProject.examples;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicNameValuePair;

public class Example2Client {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
try {
 POSTclientForm();
} catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}
 }

 public static void POSTclientForm() throws IOException {
  URL url = new URL("http://localhost:9090/StudyProject/webapi/cars2");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();

  // Create a list of type NameValuePair (interface)
  List<NameValuePair> nvList = new ArrayList<>();
  // BasicNameValuePair class implements NameValuePair interface
  // passing username and password to POST body as name value pairs
  nvList.add(new BasicNameValuePair("userName", "Demo"));
  nvList.add(new BasicNameValuePair("password", "Tester01"));

  URIBuilder newUri = new URIBuilder().setParameters(nvList);
  System.out.println(newUri.toString());

  connection.setDoOutput(true);
  connection.setRequestMethod("POST");
  // "ContentType.APPLICATION_FORM_URLENCODED" gives me
  // x-www-form-urlencoded
  connection.setRequestProperty("content-type", ContentType.APPLICATION_FORM_URLENCODED.toString());

  OutputStream os = connection.getOutputStream();
  // removing the ?
  String newString = newUri.toString().substring(1);
  System.out.println(newString);
  os.write(newString.getBytes());
  os.flush();
  InputStream inputStream = connection.getInputStream();
  BufferedInputStream bis = new BufferedInputStream(inputStream);
  while (bis.available() > 0) {
   char c = (char) bis.read();
   System.out.print(c);
  }

 }
}

OUTPUT

You have successfully logged in as Demo using Tester01


  • Example of simple @GET method using @QueryParam 


package com.sudas.study.glassfish.StudyProject.examples;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

@Path("/cars3")
public class JaxRSexample3 {
 // use of @QueryParam for @GET method

 @GET
 @Produces(MediaType.TEXT_PLAIN)
 public static String getQueryParamExample(@QueryParam("userName") String userName,
   @QueryParam("password") String password) {
  System.out.println("You have logged in as " + userName + " " + "using password " + password);
  return "You have logged in as " + userName + " " + "using password " + password;
 }

}

  • Test the method using postman


  • Test the method using custom client

package com.sudas.study.glassfish.StudyProject.examples;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicNameValuePair;

public class Example3Client {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  GETqueryString();

 }
 public static void GETqueryString() {
  List<NameValuePair> nvList = new ArrayList<>();
  nvList.add(new BasicNameValuePair("userName", "sudas"));
  nvList.add(new BasicNameValuePair("password", "password"));

  try {
   URIBuilder builder = new URIBuilder("http://localhost:9090/StudyProject/webapi/cars3");
   builder.addParameters(nvList);

   System.out.println(builder.toString());
   final String URI = builder.toString();

   try {
    URL url = new URL(URI);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.setRequestProperty("accept", ContentType.TEXT_PLAIN.toString());
    int responseCode = connection.getResponseCode();
    System.out.println(responseCode);

    BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
    while (bis.available() > 0) {
     char c = (char) bis.read();
     System.out.print(c);
    }

   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

  } catch (URISyntaxException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }
 
}

OUTPUT

You have logged in as sudas using password password
  • For a complete list of MIME ("Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format) click here

This example illustrates sending JSON in body of @POST request 

  • Example -- method using @PathParam Jersey annotation



Example URI
http://localhost:9090/StudyProject/webapi/query/hello,world 

  • Example -- method using @MatrixParam Jersey annotation

Example URI
http://localhost:9090/StudyProject/webapi/query;name=sss;age=22



Thursday, April 7, 2016

JACKSON API for JSON

Jackson is very powerful simple to use high performance API :-) Jackson is used to serialize and de serialize java object to JSON and JSON to java objects respectively.

Main components of Jackson are

  • - Data Binding which contains the object mapper
  • - Annotation and
  • - Jackson core


In Jackson api there is no need for a separate mapping to serialize java objects to json 


Jackson JSON Tree Model

Jackson has a built-in tree model which can be used to represent a JSON object. Jackson's tree model is useful if you don't know how the JSON you will receive looks, or if you for some reason cannot (or just don't want to) create a class to represent it.

Jackson process JSON in 3 different ways

Streaming API - 
JSON Parser reads data and JSON Generator writes data

Tree Model -
Creates an in memory tree structure of the JSON document like DOM. Object mapper build tree of JSON nodes.

The Jackson tree model is represented by the JsonNode class. You use the Jackson ObjectMapper to parse JSON into a JsonNode tree model, just like you would have done with your own class.

Object mapper builds the tree and tree consists of JSON Nodes 

Data Binding - 
  • It converts JSON to and from Plain Old Java Object (POJO) using property accessor or using annotations. ObjectMapper reads/writes JSON for both types of data bindings. Data binding is analogous to JAXB parser for XML. Data binding is of two types −
    • Simple Data Binding − It converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans, and null objects.
    • Full Data Binding − It converts JSON to and from any Java type.
Streaming API Example


Example of JSON PARSER using Streaming API




 public static void jacksonJSONparser() {  
           String fruitJSON = "{ \"name\" : \"apple\", \"quantity"\" : 5 }";  
           JsonFactory jfactory = new JsonFactory();  
           try {  
                JsonParser parser = jfactory.createParser(fruitJSON);  
                while (!parser.isClosed()) {  
                     JsonToken token = parser.nextToken();  
                     // System.out.println(token);  
                     if (JsonToken.FIELD_NAME.equals(token)) {  
                          String fieldName = parser.getCurrentName();  
                          System.out.println(fieldName);  
                          parser.nextToken();  
                          if (fieldName.equals("brand")) {  
                               System.out.println(parser.getValueAsString());  
                          }  
                          if (fieldName.equals("doors")) {  
                               System.out.println(parser.getValueAsInt());  
                          }  
                     }  
                }  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  

OR to get all the Name an Value simple use



 if (fieldName.equals(fieldName)) {  
                               System.out.println(parser.getValueAsString());  
                          }  



A more complex JSON read using Jackson streaming API





Code To read the JSON



 public static void jacksonJSONparser() {  
           String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";  
           JsonFactory jfactory = new JsonFactory();  
           try {  
                JsonParser parser = jfactory.createParser(new File("/Users/S_Das/Documents/Java/sudas.com.au/user.json"));  
                while (!parser.isClosed()) {  
                     JsonToken token = parser.nextToken();  
                     // System.out.println(token);  
                     if (JsonToken.FIELD_NAME.equals(token)) {  
                          String fieldName = parser.getCurrentName();  
                          System.out.println("name: "+fieldName);  
                          parser.nextToken();  
                          if (fieldName.equals(fieldName) && parser.getValueAsString() !=null) {  
                               System.out.println("value: "+parser.getValueAsString());  
                          }  
                     }  
                }  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  


Output:




Using Jackson Data Binding converting a POJO to JSON




My POJO class


 package com.rest.client;  
 import java.util.List;  
 public class UserModel {  
      String firstName;  
      String lastName;  
      String address;  
      int age;  
      List<String> hobbies;  
      public UserModel() {  
           // TODO Auto-generated constructor stub  
      }  
      public UserModel(String firstName, String lastName, String address, int age, List<String> hobbies) {  
           super();  
           this.firstName = firstName;  
           this.lastName = lastName;  
           this.address = address;  
           this.age = age;  
           this.hobbies = hobbies;  
      }  
      public String getFirstName() {  
           return firstName;  
      }  
      public void setFirstName(String firstName) {  
           this.firstName = firstName;  
      }  
      public String getLastName() {  
           return lastName;  
      }  
      public List<String> getHobbies() {  
           return hobbies;  
      }  
      public void setHobbies(List<String> hobbies) {  
           this.hobbies = hobbies;  
      }  
      public void setLastName(String lastName) {  
           this.lastName = lastName;  
      }  
      public String getAddress() {  
           return address;  
      }  
      public void setAddress(String address) {  
           this.address = address;  
      }  
      public int getAge() {  
           return age;  
      }  
      public void setAge(int age) {  
           this.age = age;  
      }  
 }  


Code to convert POJO to JSON and write to a file


 package com.rest.client;  
 import java.io.File;  
 import java.io.IOException;  
 import java.util.ArrayList;  
 import java.util.Arrays;  
 import java.util.List;  
 import com.fasterxml.jackson.databind.ObjectMapper;  
 public class JacksonDataBinding {  
      public static void main(String[] args) {  
           createJSON();  
      }  
      public static void createJSON() {  
           List<String> hobbies = new ArrayList<>();  
           List<String> lists = Arrays.asList("Java Coding", "Car Driving", "DIY");  
           hobbies.addAll(lists);  
           UserModel userOne = new UserModel("subhra", "das", "India", 35, hobbies);  
           ObjectMapper mapper = new ObjectMapper();  
           try {  
                // convert user object to json and writes to file  
                mapper.writeValue(new File("/Users/S_Das/Documents/Java/sudas.com.au/Newuser.json"), userOne);  
                // convert user object to json and prints in pretty format  
                System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(userOne));  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  



Update Name Value in JSON


      public static void modifyJSON()  
      {  
           ObjectMapper mapper = new ObjectMapper();  
      try {  
           JsonNode tree = mapper.readTree(new File("/Users/S_Das/Documents/Java/sudas.com.au/Newuser.json"));  
           String printPretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(tree);  
           System.out.println(printPretty);  
           // Changing field name value in json  
           ((ObjectNode)tree).put("firstName", "Sharanya");  
           String printPretty1 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(tree);  
           System.out.println(printPretty1);  
           //writing the changed value to file  
           mapper.writeValue(new File("/Users/S_Das/Documents/Java/sudas.com.au/Newuser.json"), tree);  
           System.out.println(tree.path("lastName").asText());  
      } catch (IOException e) {  
           // TODO Auto-generated catch block  
           e.printStackTrace();  
      }  
      }  

Hello World

Monday, April 4, 2016

REST api client

This is a REST API client which behaves similar to any other REST clients like POSTMAN. As an example I am illustrating GET and POST request. In POST request I am reading JSON from file and feeding the JSON as inputstream to the connection object

This is the JSON which I am sending as InputStream



 package com.rest.client;  
 import java.io.BufferedInputStream;  
 import java.io.BufferedOutputStream;  
 import java.io.BufferedReader;  
 import java.io.BufferedWriter;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 import java.io.OutputStream;  
 import java.net.HttpURLConnection;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 import java.net.URLConnection;  
 import org.apache.commons.io.IOUtils;  
 public class RESTclient {  
      private static final String ADDRESS = "http://localhost:9090/StudyProject/webapi/phonebooks";  
      public static void main(String[] args) {  
           /*  
            * HttpURLConnection connection = null; try { connection = GETclient();  
            * } catch (IOException e) { // TODO Auto-generated catch block  
            * e.printStackTrace(); } finally { connection.disconnect(); }  
            */  
           try {  
                POSTclient();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
      public static HttpURLConnection GETclient() throws IOException {  
           URL url = new URL(ADDRESS);  
           // using HTTP URL connection object  
           HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
           connection.setRequestMethod("GET");  
           connection.setRequestProperty("accept", "application/json");  
           int responseCode = connection.getResponseCode();  
           System.out.println(responseCode);  
           BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());  
           while (bis.available() > 0) {  
                char c = (char) bis.read();  
                System.out.print(c);  
           }  
           return connection;  
      }  
      // http://bernhardhaeussner.de/odd/json-escape/  
      public static void POSTclient() throws IOException {  
           URL url = new URL(ADDRESS);  
           HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
           connection.setDoOutput(true);  
           connection.setRequestMethod("POST");  
           connection.setRequestProperty("content-type", "application/json");  
           // String json = "";  
           BufferedInputStream inputStream = new BufferedInputStream(  
                     new FileInputStream(new File("/Users/S_Das/Desktop/user.json")));  
           byte[] json = IOUtils.toByteArray(inputStream);  
           OutputStream os = connection.getOutputStream();  
           // sending a byte stream  
           os.write(json);  
           os.flush();  
           BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());  
           while (bis.available() > 0) {  
                char c = (char) bis.read();  
                System.out.print(c);  
           }  
      }  
 }  

REST API Implementation

This is a simple application where I am creating phone book entries. Each phone book entries must have First Name , Phone Number along with Last Name and Email address.

This application is developed though REST API.


PhoneBook model class
This is the phonebook POJO class
 package com.sudas.study.glassfish.StudyProject.phonebook;  
 public class PhoneBookModel {  
      String phoneNumber;  
      String firstName;  
      String lastName;  
      String email;  
      public PhoneBookModel() {  
           // TODO Auto-generated constructor stub  
      }  
      public PhoneBookModel(String phoneNumber, /*String firstName,*/ String lastName, String email) {  
           super();  
           this.phoneNumber = phoneNumber;  
 //          this.firstName = firstName;  
           this.lastName = lastName;  
           this.email = email;  
      }  
      public String getPhoneNumber() {  
           return phoneNumber;  
      }  
      public void setPhoneNumber(String phoneNumber) {  
           this.phoneNumber = phoneNumber;  
      }  
      public String getFirstName() {  
           return firstName;  
      }  
      public void setFirstName(String firstName) {  
           this.firstName = firstName;  
      }  
      public String getLastName() {  
           return lastName;  
      }  
      public void setLastName(String lastName) {  
           this.lastName = lastName;  
      }  
      public String getEmail() {  
           return email;  
      }  
      public void setEmail(String email) {  
           this.email = email;  
      }  
 }  

Stage - I
Here I am creating different phonebook model object and passing parameters through argument constructor in phonebook class.
The GET method is used to get all the phone numbers
The POST method is used to add more phone numbers



 package com.sudas.study.glassfish.StudyProject.phonebook;  
 import java.util.ArrayList;  
 import java.util.HashMap;  
 import java.util.List;  
 import java.util.Map;  
 import javax.ws.rs.Consumes;  
 import javax.ws.rs.GET;  
 import javax.ws.rs.POST;  
 import javax.ws.rs.Path;  
 import javax.ws.rs.Produces;  
 import javax.ws.rs.core.MediaType;  
 @Path("/phonebook")  
 public class PhoneNumber {  
      static Map<Integer, PhoneBookModel> phMap = new HashMap<>();  
      // this is a stub which creates a map  
      public static void dbStub() {  
           phMap.put(001, new PhoneBookModel("9527620368", "Das", "subhra.s.das@gmail.com"));  
           phMap.put(002, new PhoneBookModel("9730040163", "Das", "pranatidas2004@gmail.com"));  
      }  
      @GET  
      @Produces(MediaType.APPLICATION_JSON)  
      // this method returns all the phone number added in dbStub  
      public static List<PhoneBookModel> getAllPhoneNumbers() {  
           dbStub();  
           List<PhoneBookModel> phoneList = new ArrayList<>(phMap.values());  
           return phoneList;  
      }  
      @POST  
      @Consumes(MediaType.APPLICATION_JSON)  
      @Produces(MediaType.APPLICATION_JSON)  
      public static List<PhoneBookModel> addPhoneNumber(PhoneBookModel phmodel) {  
           // calling the db stub to add existing entries  
           dbStub();  
           int size = phMap.size();  
           System.out.println(size + 2);  
           // adding a new phone number to the existing map  
           phMap.put(size + 2, phmodel);  
           return getAllPhoneNumbers();  
      }  
 }  

Stage - II
This class can POST array of JSON objects




 package com.sudas.study.glassfish.StudyProject.phonebook;  
 import java.util.ArrayList;  
 import java.util.List;  
 import javax.ws.rs.Consumes;  
 import javax.ws.rs.GET;  
 import javax.ws.rs.POST;  
 import javax.ws.rs.Path;  
 import javax.ws.rs.Produces;  
 import javax.ws.rs.core.MediaType;  
 @Path("/phonebooks")  
 public class PhoneNumbers {  
      static List<PhoneBookModel> list = new ArrayList<>();  
      public static List<PhoneBookModel> dbStub() {  
           list.add(new PhoneBookModel("9527620368", "Das", "subhra.s.das@gmail.com"));  
           list.add(new PhoneBookModel("9730040163", "Das", "pranatidas2004@gmail.com"));  
           return list;  
      }  
      @GET  
      @Consumes(MediaType.APPLICATION_JSON)  
      public static List<PhoneBookModel> getAllNumbers() {  
           return dbStub();  
      }  
      @POST  
      @Consumes(MediaType.APPLICATION_JSON)  
      @Produces(MediaType.APPLICATION_JSON)  
      public static List<PhoneBookModel> addNumbers(List<PhoneBookModel> phoneNumbers) {  
           list.addAll(phoneNumbers);  
           return list;  
      }  
      public static void main(String[] args) {/*  
           dbStub();  
           List<PhoneBookModel> l = Arrays.asList(new PhoneBookModel("9999999999", "Das", "sharanya.das@icloud.com"));  
           List<PhoneBookModel> newList = addNumbers(l);  
           for (int i = 0; i < newList.size(); i++) {  
                System.out.println(newList.get(i).getPhoneNumber());  
           }  
      */}  
 }  

Illustrating GET and POST request through POSTMAN





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();  
      }  
 }