Smiley face

Saturday, 4 January 2014

RESTful Web service with Jersey Client

In this tutorials we are going to see the how to access the RESTful web service using jersey client API.
Here i am going to create two clients to access GET and POST request . Add jersey-client-1.17.1.jar  in build path
GET Request
Refer this example for creating service http://www.javatutorialscorner.com/2014/01/jax-rs-get-using-restful-webservice.html
After create and run the service then create java client  as given below
RESTJerseyClient.java
package com.javatutorialscorner.jaxrs.client;

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

public class RESTJerseyClient {
 public static void main(String[] args) {
  String baseURI = "http://localhost:8080/RESTful-WebService";
  Client client = Client.create();
  WebResource service = client.resource(baseURI);
  System.out.println(service.path("rest")
    .path("getservice/javatutorialscorner.com")
    .get(ClientResponse.class).getEntity(String.class));
 }
}

Now run the client program see the following output in console

Web Site : javatutorialscorner.com

POST Request
Refer this example for creating service http://www.javatutorialscorner.com/2014/01/jax-rx-post-using-restful-web-service.html

After create and run the service then create java client  as given below

RESTJerseyClient.java

package com.javatutorialscorner.jaxrs.client;

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

public class RESTJerseyClient {
 public static void main(String[] args) {
  try {
   String baseURI = "http://localhost:8080/RESTful-WebService/rest/restfulpost/post";
   Client client = Client.create();
   WebResource service = client.resource(baseURI);
   String json = "{\"name\":\"Ram\",\"id\":33,\"department\":\"EEE\",\"year\":2011}";
   ClientResponse response = service.type("application/json").post(
     ClientResponse.class, json);

   if (response.getStatus() != 201) {
    throw new Exception("Error code : " + response.getStatus());
   }

   System.out.println(response.getEntity(String.class));
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

Now run the client program see the following output in console

Data Received Successfuly : Ram

0 comments

Post a Comment

 

Receive all updates via Facewbook. Just Click the Like Button Below

Help us ! Shop @ Flipkat by click the Advertisement in JTC

Help us ! Shop @ Flipkat by click the Advertisement in JTC's

Help us ! Shop @ Amazon.com by click the Advertisement in JTC's