Quantcast
Viewing all articles
Browse latest Browse all 1037

How to Create RESTful Java Client With Jersey Client – Example

Image may be NSFW.
Clik here to view.
RESTful Service Client Example - Crunchify Tutorial

This tutorial show you how to use Jersey client APIs to create a RESTful Java client to perform “GET” requests to REST service that created in this How to build RESTful Service with Java using JAX-RS and Jersey (Example) example.

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}

The post How to Create RESTful Java Client With Jersey Client – Example appeared first on Crunchify.

Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 1037

Trending Articles