How to Create RESTful Java Client With Java.Net.URL – Example

Last updated
App Shah
Crunchify » Java and J2EE Tutorials » How to Create RESTful Java Client With Java.Net.URL – Example
how-to-create-restful-java-client-with-java-net-url-example

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>

2 thoughts on “How to Create RESTful Java Client With Java.Net.URL – Example”

  1. Hey Guys, adding complete project structure snapshot here just incase you need to get information on all required jars to build RESTFul service and all 3 clients mentioned above…

    Keep Sharing and Happy Coding.

    Reply

Leave a Comment