Image may be NSFW.
Clik here to view.
This tutorial show you how to use Apache HttpClient 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.
Pre-requirement: Deploy above mentioned project successfully on Tomcat.
Make sure your Web Server Tomcat is running and URL http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/ is accessible.
package com.crunchify.client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; /** * @author Crunchify.com * */ public class CrunchifyRESTJerseyApacheHTTPClient { public static void main(String[] args) { try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet("http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/"); getRequest.addHeader("accept", "application/xml"); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("============Output:============"); while ((output = br.readLine()) != null) { System.out.println(output); } httpClient.getConnectionManager().shutdown(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Output:
============Output:============ <ctofservice><celsius>36.8</celsius><ctofoutput>@Produces("application/xml") Output: C to F Converter Output: 98.24</ctofoutput></ctofservice>
Other must read:
- Hello World Example – Spring MVC 3.2.1
- How to Create RESTful Java Client With Jersey Client – Example
- How to Create RESTful Java Client With Java.Net.URL – Example
The post How to Create RESTful Java Client using Apache HttpClient – Example appeared first on Crunchify.
Clik here to view.