Friday, December 5, 2014

Client Implementation for REST web service with Jersy


In this post I will explain how to implement a client application to the RESTfull web service created in my previous post.

I'm going to use Jersy client API for this.

Here is the client Java class.

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

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: manorama
 * Date: 12/4/14
 * Time: 4:41 PM
 * To change this template use File | Settings | File Templates.
 */
public class RESTClient {

    private static final Logger logger = Logger.getLogger(RESTClient.class.getName());

    public static void main(String[] args) {

        try {
            // GET request
            demoGET();

            // POST request
            demoPOST();
        } catch (Exception e)
        {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

    private static void demoPOST() {

        Client client = Client.create();

        WebResource webResource = client
                .resource("http://localhost:9090/RESTfulWS/musicservice/tracks");

        String input = "{\"singer\":\"Metallica\",\"title\":\"Fade To Black\"}";

        ClientResponse response = webResource.type("application/json")
                .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);
    }

    /**
     * GET request
     */
    private static void demoGET() {

        Client client = Client.create();

        WebResource webResource = client
                .resource("http://localhost:9090/RESTfulWS/musicservice/randomtracks");

        ClientResponse response = webResource.accept("application/json")
                .get(ClientResponse.class);

        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatus());
        }

        String output = response.getEntity(String.class);

        System.out.println("Output from Server .... \n");
        System.out.println(output);
    }

}


References:

[1] http://crunchify.com/how-to-create-restful-java-client-with-jersey-client-example/
[2] http://crunchify.com/how-to-create-restful-java-client-using-apache-httpclient-example/

No comments: