Quantcast
Channel: Crunchify
Viewing all articles
Browse latest Browse all 1037

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

$
0
0

Crunchify RESTJersey Java.Net.URL Client Example

This tutorial show you how to use Java.Net.URL 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.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();
	}
}

Output:

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>

List of more than 150 Java Tutorials.

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


Viewing all articles
Browse latest Browse all 1037

Trending Articles