Sunday, November 25, 2012

REST WEBSERVICE - JERSEY CLIENT API

               REST WEBSERVICE - JERSEY CLIENT API 


Jersy is a Open Source Implementation of JAX-RS used to create RESTful Webservices using Java.

import com.sun.jersey.api.client.Client;

Client client = Client.create();

creating a instance of a Client is an expensive operation so re-use it after initializing for the first time.

create a WebResource object, which encapsulates a web resource for the client. 

   import com.sun.jersey.api.client.WebResource;

   WebResource webResource = client.resource("http://example.com/base");


use WebResource object to build requests to send to the web resource and to process responses returned from the web resource. For example, you can use the WebResource object for HTTP GET, PUT, POST, and DELETE requests.

String s = webResource.get(String.class);

Download Jersey Resource bundle  Jersey-bundle and add jars to the classpath.

  public String sendRestRequest(String restUrl) {
       
        String response = null;   
        Client client =  Client.create();
        WebResource webResource = client.resource(restUrl);
        
// response type returned from the REST resource is XML or JSON

         ClientResponse clientResponse = webResource.accept(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE).get(ClientResponse.class);
        try {
// If status code returned is not 200 throw error
            if (clientResponse.getStatus() != 200) {
                System.out.println(" \n Rest URL : " + restUrl +
                          " Failed with HTTP error code : " +
                          clientresponse.getStatus());
                return null;
            }
            response = clientResponse.getEntity(String.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
// JSON response
        return response;
    }

How to pass authentication parameters along with Client request

import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

use HTTPBasicAuthFilter to pass username and password.

      HTTPBasicAuthFilter authFilter =
            new HTTPBasicAuthFilter(username, pwd);
      client.addFilter(authFilter);
      WebResource webResource = client.resource(restUrl);

How to pass Custom Headers along with client request

 ClientResponse clientResponse = webResource.accept(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE).header("Custom-header",headerValue).get(ClientResponse.class);

Saturday, November 24, 2012

JSON PARSER - USING JERSEY

                                 JSON PARSER - USING JERSEY


Now a days most of the companies building webservices using REST instead of SOAP.

Representational State Transfer or REST basically means that each unique URL is a representation of some object. You can get the contents of that object using an HTTP GET, to delete it, you then might use a POST, PUT, or DELETE to modify the object .

REST uses existing principles and protocols of the Web are enough to create robust Web services. This means that developers who understand HTTP and XML can start building Web services right away, without needing any toolkits beyond what they normally use for Internet application development.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
In JSON, they take on these forms:

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.


{
"employees": [
{ "firstName":"Raghu" , "lastName":"Juluri" }, 
{ "firstName":"Dinesh" , "lastName":"Gunda" }, 
{ "firstName":"Kumar" , "lastName":"Prabhu" }
]
}

JSON object can be parsed using jersey. 

Download Jersey Resource bundle  jersey-bundle.jar , JSON and add jars to the classpath.


     public void parseJson(String json) {

        try {
            JSONObject jsonObj = new JSONObject(json);


            String[] keys = JSONObject.getNames(jsonObj);
            for (String key : keys) {

                if (jsonObj.get(key) instanceof JSONObject) {
                    JSONObject innerData = jsonObj.getJSONObject(key);
                    // process inner Json Object
                } else if (jsonObj.get(key) instanceof JSONArray) {
                    JSONArray innerArray = jsonObj.getJSONArray(key);
                    for (int i = 0; i < innerArray.length(); i++) {
                        JSONObject innerJsonArray = innerArray.getJSONObject(i);
                        //Process JSON Object present in the Array }
                    }
                } else {
                    System.out.println("Key : " + key + " Value : " +
                                       jsonObj.get("key"));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }




Popular Posts