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

No comments:

Popular Posts