
This tutorial show you how to use Java.Net.URL 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 java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
/**
* @author Crunchify.com
*
*/
public class CrunchifyRESTJerseyNetURLClient {
public static void main(String[] args) {
System.out.println("\n============Output:============ \n" + callURL("http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/"));
}
public static String callURL(String myURL) {
System.out.println("Requested URL: " + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
urlConn.setReadTimeout(60 * 1000);
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:" + myURL, e);
}
return sb.toString();
}
}
Eclipse Console Result:
Requested URL: http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/
============Output:============
<ctofservice><celsius>36.8</celsius><ctofoutput>@Produces("application/xml") Output:
C to F Converter Output:
98.24</ctofoutput></ctofservice>
