rest

RESTful Java Client With java.net.URL

In this example we are going to see how you can use java.net package utilities, to create RESTful  clients that can consume simpele REST Services. It is not the easiest way to create a RESTful client, as you have to read the response yourself, as well as marshal and unmarshal Java Objects to some kind of stream, if that’s what is necessary.

If you want to use a reference implementation and you don’t want to deal with other clients, like Jersey or RESTEasy, this example will guide you through.

In this example we are not going to focus on how to create a JAX-RS application from top to bottom. So make sure you read carefully Jersey Hello World Example  and pay attention to the sections concerning the creation of the project with Eclipse IDEas well as the deployment of the project in Tomcat.

You can create your own project following the instructions on Jersey Hello World Example. But you can also download the Eclipse project of this tutorial here : JAXRS-HelloWorld.zip, and build your new code on top of that.

Additionally we are going to use the REST Service endpoint created in : JSON Example With Jersey + Jackson. You can download and use the code of this example here : JerseyJSONExample.zip.

1. Project structure

For this example, I’ve created a new Project called “JerseyJSONExample“. You can see the structure of the NEW project in the image below:

project-struvture

2. REST Service Endpoint

Let’s remind ourselves of the classes that composes the Service endpoint that we are going to use:

JerseyRestService.java:

package com.javacodegeeks.enterprise.rest.jersey;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/jsonServices")
public class JerseyRestService {

	@GET
	@Path("/print/{name}")
	@Produces(MediaType.APPLICATION_JSON)
	public Student produceJSON( @PathParam("name") String name ) {

		Student st = new Student(name, "Diaz",22,1);

		return st;

	}

	@POST
	@Path("/send")
	@Consumes(MediaType.APPLICATION_JSON)
	public Response consumeJSON( Student student ) {

		String output = student.toString();

		return Response.status(200).entity(output).build();
	}
}

And here is the class that is going to be represented in JSON format:

Student.java:

package com.javacodegeeks.enterprise.rest.jersey;

public class Student {

	private int id;
	private String firstName;
	private String lastName;
	private int age;

	// Must have no-argument constructor
	public Student() {

	}

	public Student(String fname, String lname, int age, int id) {
		this.firstName = fname;
		this.lastName = lname;
		this.age = age;
		this.id = id;
	}

	public void setFirstName(String fname) {
		this.firstName = fname;
	}

	public String getFirstName() {
		return this.firstName;
	}

	public void setLastName(String lname) {
		this.lastName = lname;
	}

	public String getLastName() {
		return this.lastName;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int getAge() {
		return this.age;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getId() {
		return this.id;
	}

	@Override
	public String toString() {
		return new StringBuffer(" First Name : ").append(this.firstName)
				.append(" Last Name : ").append(this.lastName)
				.append(" Age : ").append(this.age).append(" ID : ")
				.append(this.id).toString();
	}

}

3. GET Request with java.net Client

To host the code of this client, I’ve created a new package under /src/main/java called com.javacodegeeks.enterprise.rest.javaneturlclient, as you can see in the above image.

So here is the code to perform a simle GET Request:

JavaNetURLRESTFulClient.java:

package com.javacodegeeks.enterprise.rest.javaneturlclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class JavaNetURLRESTFulClient {

	private static final String targetURL = "http://localhost:8080/JerseyJSONExample/rest/jsonServices/print/Jamie";

	public static void main(String[] args) {

		  try {

			URL restServiceURL = new URL(targetURL);

			HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
			httpConnection.setRequestMethod("GET");
			httpConnection.setRequestProperty("Accept", "application/json");

			if (httpConnection.getResponseCode() != 200) {
				throw new RuntimeException("HTTP GET Request Failed with Error code : "
						+ httpConnection.getResponseCode());
			}

			BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
				(httpConnection.getInputStream())));

			String output;
			System.out.println("Output from Server:  \n");

			while ((output = responseBuffer.readLine()) != null) {
				System.out.println(output);
			}

			httpConnection.disconnect();

		  } catch (MalformedURLException e) {

			e.printStackTrace();

		  } catch (IOException e) {

			e.printStackTrace();

		  }

		}
}

As you can see we create an HTTP connection with the endpoint and send a GET request, while setting the Accept header to “application/json“.Then, we read the response body line by line, and append it to a String. Notice that if you want to marshal the response to a Student instance you have to do it your self.

Now if you run he above client here is the output:

Output:

Output from Server:  

{"id":1,"firstName":"Jamie","age":22,"lastName":"Diaz"}

4. POST Request with java.net Client

Now let’s see what you can do to send a JSON formated POST request to our endpoint.

JavaNetURLRESTFulClient.java:

package com.javacodegeeks.enterprise.rest.javaneturlclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class JavaNetURLRESTFulClient {

	private static final String targetURL = "http://localhost:8080/JerseyJSONExample/rest/jsonServices/send";

	public static void main(String[] args) {

		try {

			URL targetUrl = new URL(targetURL);

			HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
			httpConnection.setDoOutput(true);
			httpConnection.setRequestMethod("POST");
			httpConnection.setRequestProperty("Content-Type", "application/json");

			String input = "{\"id\":1,\"firstName\":\"Liam\",\"age\":22,\"lastName\":\"Marco\"}";

			OutputStream outputStream = httpConnection.getOutputStream();
			outputStream.write(input.getBytes());
			outputStream.flush();

			if (httpConnection.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
					+ httpConnection.getResponseCode());
			}

			BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
					(httpConnection.getInputStream())));

			String output;
			System.out.println("Output from Server:\n");
			while ((output = responseBuffer.readLine()) != null) {
				System.out.println(output);
			}

			httpConnection.disconnect();

		  } catch (MalformedURLException e) {

			e.printStackTrace();

		  } catch (IOException e) {

			e.printStackTrace();

		 }

		}	 
}

In the above code we attempt to send a JSON formatted String to our endpoint. We enable the output option on the HTTP connection, with httpConnection.setDoOutput(true) because we actually want to add a Request body, that is the JSON string. It is quite easy to create a JSON formatted string by hand, that’s "{\"id\":1,\"firstName\":\"Liam\",\"age\":22,\"lastName\":\"Marco\"}" in our case. If you want to marshal a Student object to JSON format you have to do it yourself.

Now if you run he above client here is the output:

Output:

Output from Server:

First Name : Liam Last Name : Marco Age : 22 ID : 1

Download Eclipse Project

This was a RESTful Java Client With java.net.URL. Download the Eclipse Project of this example: JavaNetURLRESTFulClient.zip

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Arnaud
Arnaud
6 years ago

Thank you for this awesome post. I have just a little remark : in paragraph “GET Request with java.net Client” the transformation from JSON to Java is unmarshallling (or deserialization) and not marshalling.

Back to top button