This tutorial show you how to use Jersey client APIs
to create a RESTful
Java client to perform “GET
” requests to REST service.
Pre-requirement:
Deploy Project How to build RESTful Service with Java using JAX-RS and Jersey (Example).
Make sure your Web Server Tomcat is running and URL http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/ is accessible.
package com.crunchify.client; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; /** * @author Crunchify * */ public class CrunchifyRESTJerseyClient { public static void main(String[] args) { CrunchifyRESTJerseyClient crunchifyClient = new CrunchifyRESTJerseyClient(); crunchifyClient.getCtoFResponse(); crunchifyClient.getFtoCResponse(); } private void getFtoCResponse() { try { Client client = Client.create(); WebResource webResource2 = client.resource("http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ftocservice/90"); ClientResponse response2 = webResource2.accept("application/json").get(ClientResponse.class); if (response2.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response2.getStatus()); } String output2 = response2.getEntity(String.class); System.out.println("\n============getFtoCResponse============"); System.out.println(output2); } catch (Exception e) { e.printStackTrace(); } } private void getCtoFResponse() { try { Client client = Client.create(); WebResource webResource = client.resource("http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/40"); ClientResponse response = webResource.accept("application/xml").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("============getCtoFResponse============"); System.out.println(output); } catch (Exception e) { e.printStackTrace(); } } }
Output:
============getCtoFResponse============ <ctofservice><celsius>40.0</celsius><ctofoutput>@Produces("application/xml") Output: C to F Converter Output: 104.0</ctofoutput></ctofservice> ============getFtoCResponse============ @Produces("application/json") Output: F to C Converter Output: {"F Value":90,"C Value":32.22222137451172}