Monday, November 18, 2013

Implementing REST services with Java Jersey and Apache Tomcat - Client Side

Continuing from the previous post, below is some sample code implementing a Jersey client to invoke an HTTP GET to the server


/**
 * Java client to access tje REST interface to the cache.
 *
 * @author Joey Whelan
 */
public class ClientRS
{
   
    /** The service. */
    private WebResource service;
   
    /** The client. */
    private Client client;
   
    /** The logger. */
    private static Logger logger = Logger.getLogger(ClientRS.class);
    

    /**
     * Builds the REST client object
     *
     * @param spec the spec
     * @return the client rs
     */


    public static ClientRS build(String spec)
    {
        logger.debug("Entering build(spec= " + spec + ")");
        URI uri = null;
   
        try
        {
            URL url = new URL(spec);
            uri = url.toURI();
            logger.debug("Exiting build()");
            return new ClientRS(uri);
        }
        catch (Exception e)
        {
            logger.error(e);
            logger.debug("Exiting build()");
            return null;
        }
    }
      /**
     * Private constructor to instantiate a new REST client.
     *
     * @param uri the uri
     */
    private ClientRS(URI uri)
    {
        logger.debug("Entering ClientRS(uri= " + uri + ")");
        ClientConfig config = new DefaultClientConfig();
        this.client = Client.create(config);
        this.service = this.client.resource(uri);
        logger.debug("Exiting ClientRS()");
    }
   
   
    /**
     * Retrieves value from cache based on key
     *
     * @param key the key
     * @return HTTP response
     */
    public ClientResponse getValue(String key)
    {
        logger.debug("Entering getValue(key= " + key + ")");
        ClientResponse response = service.path("key").path(key).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
        logger.debug("Exiting getValue(), response= " + response);
        return response;
    }


Invocation of the client:

String rsSpec = "https://1.1.1.1:8443/ctispan/rest";
ClientRS client = ClientRS.build(rsSpec);
ClientResponse resp = null;

if (client != null) resp = client.getValue("111");
        if (resp != null)
            System.out.println("status code: " + resp.getStatus() + " entity: " +  resp.getEntity(String.class));




No comments:

Post a Comment