Main Tutorials

RESTful Java client with RESTEasy client framework

This tutorial show you how to create a RESTful Java client with RESTEasy client framework, to perform “GET” and “POST” requests to REST service that created in last “Jackson + JAX-RS” tutorial.

1. RESTEasy Client Framework

RESTEasy client framework is included in RESTEasy core module, so, you just need to declares the “resteasy-jaxrs.jar” in your pom.xml file.

File : pom.xml


	<dependency>
		<groupId>org.jboss.resteasy</groupId>
		<artifactId>resteasy-jaxrs</artifactId>
		<version>2.2.1.GA</version>
	</dependency>

2. GET Request

Review last REST service.


@Path("/json/product")
public class JSONService {

	@GET
	@Path("/get")
	@Produces("application/json")
	public Product getProductInJSON() {

		Product product = new Product();
		product.setName("iPad 3");
		product.setQty(999);
		
		return product; 

	}
	//...

RESTEasy client to send a “GET” request.


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.client.ClientProtocolException;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;

public class RESTEasyClientGet {

	public static void main(String[] args) {
	  try {

		ClientRequest request = new ClientRequest(
				"http://localhost:8080/RESTfulExample/json/product/get");
		request.accept("application/json");
		ClientResponse<String> response = request.get(String.class);

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

		BufferedReader br = new BufferedReader(new InputStreamReader(
			new ByteArrayInputStream(response.getEntity().getBytes())));

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

	  } catch (ClientProtocolException e) {

		e.printStackTrace();

	  } catch (IOException e) {

		e.printStackTrace();

	  } catch (Exception e) {

		e.printStackTrace();

	  }

	}

}

Output…


Output from Server .... 

{"qty":999,"name":"iPad 3"}

3. POST Request

Review last REST service also.


@Path("/json/product")
public class JSONService {

        @POST
	@Path("/post")
	@Consumes("application/json")
	public Response createProductInJSON(Product product) {

		String result = "Product created : " + product;
		return Response.status(201).entity(result).build();
		
	}
	//...

RESTEasy client to send a “POST” request.


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;

public class RESTEasyClientPost {

	public static void main(String[] args) {

	  try {

		ClientRequest request = new ClientRequest(
			"http://localhost:8080/RESTfulExample/json/product/post");
		request.accept("application/json");

		String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
		request.body("application/json", input);
			
		ClientResponse<String> response = request.post(String.class);

		if (response.getStatus() != 201) {
			throw new RuntimeException("Failed : HTTP error code : "
				+ response.getStatus());
		}

		BufferedReader br = new BufferedReader(new InputStreamReader(
			new ByteArrayInputStream(response.getEntity().getBytes())));

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

	  } catch (MalformedURLException e) {

		e.printStackTrace();
			
	  } catch (IOException e) {

		e.printStackTrace();

	  } catch (Exception e) {

		e.printStackTrace();

	  }

	}

}

Output…


Output from Server .... 

Product created : Product [name=iPad 4, qty=100]

Download Source Code

References

  1. Jackson Official Website
  2. RESTful Java client with java.net.URL
  3. RESTful Java client with Apache HttpClient

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
20 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Syed
5 years ago

nice simple tutorial

Isn’t the idea of REST to be more noun centric than verb centric.
you have get and post in the URLs. Should it have ended at
…/product/
and then you either make a get call or post call and in the JsonService it will either call the method that is annotated with @GET or with @POST, Just making sure i get the idea correctly.

RAvish
6 years ago

how to access the https urls?

Prade EP Joshi
7 years ago

the code build well while i am running client class getting this error .
java.net.ConnectException: Connection refused: connect

Savani
8 years ago

Could you please update your tutorial to use reasteasy version 3.0.x version? It would help a lot to me..

ricardogobbo
8 years ago

How can I test a REST request using JUnit?

algosub
8 years ago

I tried to implement a similar client, but I need to also set a timeout for the connection. Is there a way to do it?
every way I try doesn’t work (currently I am trying to create a client request with an executor, but it does not work)

VK
9 years ago

while using the above code, I am getting following error :
java.lang.RuntimeException: Failed : HTTP error code : 500
at com.mkyong.rest.client.RESTEasyClientGet.main(RESTEasyClientGet.java:22)

reska
9 years ago

Hi.
How can i use Resteasy without maven ?

Ankita
9 years ago

Thanks. It helped me.

Eric
10 years ago

Hi,if I set this json to chinese,there is a error
String input = “{\”qty\”:100,\”name\”:\”iPad 4\”}”;=>String input = “{\”qty\”:100,\”name\”:\”??\”}”;
could you pls help?Thanks a lot 😀

Santiago Hurtado
11 years ago

Hi I´m pretty new in rest, but I will like to know how I can notify my client when a new item is added? something like MVC I guess

Thanks

hamza
9 years ago

i look for this too !!
maybe web-socket resolve the problem

pappa
11 years ago

I am getting the following error with a ClientResponseFailureException
“Unable to find a MessageBodyReader of content-type application/json and type class java.lang.String”
I tried exactly the same code as yours. Can you please help me out?

garry
10 years ago
Reply to  pappa

Im getting the same error. please help

Safi
10 years ago
Reply to  garry

Download the latest RESTEasy package (3.0.1.Final) and in the lib folder you will find the jars you need to include in your project. To fix this particular error, you need to include the various jackson related jars (jackson-jaxrs-1.9.12.jar, jackson-mapper-asl-1.9.12.jar, etc.)

Adheep
11 years ago

I’m getting “peer not authenticated” error when I’m trying to use SSL/HTTPS configuration in production environment JBoss 7AS. But works like a charm with HTTP, Is there any configuration to be added that I’m missing?

raj
11 years ago

while running post code i’m getting below error. any clue? I have added all required jars to build path as well.

Exception in thread “main” java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.jboss.resteasy.core.LoggerCategories.getLogger(LoggerCategories.java:64)
at org.jboss.resteasy.core.LoggerCategories.getProviderLogger(LoggerCategories.java:86)
at org.jboss.resteasy.plugins.providers.RegisterBuiltin.(RegisterBuiltin.java:22)
at org.jboss.resteasy.spi.ResteasyProviderFactory.getInstance(ResteasyProviderFactory.java:324)
at org.jboss.resteasy.client.ClientRequest.(ClientRequest.java:135)
at org.jboss.resteasy.client.ClientRequest.(ClientRequest.java:130)
at org.jboss.resteasy.client.ClientRequest.(ClientRequest.java:125)
at com.ca.saas.deployment.deployment.main(deployment.java:18)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 8 more

Abhijit Sarkar
12 years ago

Reading the JSON string seems to work ok but RESTEasy stumbles with unmarshaling the response even for a simple POJO. When I tried, I got the following:
<pre lang="java"
org.jboss.resteasy.client.ClientResponseFailure: Unable to find a MessageBodyReader of content-type text/html and type null
at org.jboss.resteasy.client.core.BaseClientResponse.createResponseFailure(BaseClientResponse.java:522)
at org.jboss.resteasy.client.core.BaseClientResponse.createResponseFailure(BaseClientResponse.java:513)
at org.jboss.resteasy.client.core.BaseClientResponse.readFrom(BaseClientResponse.java:414)
at org.jboss.resteasy.client.core.BaseClientResponse.getEntity(BaseClientResponse.java:376)
at org.jboss.resteasy.client.core.BaseClientResponse.getEntity(BaseClientResponse.java:337)
at name.app.abhi.imdb.api.accessor.IMDBAPIClient.getMovieInfo(IMDBAPIClient.java:37)
at name.app.abhi.imdb.api.accessor.IMDBAPIClientTest.testSendRequestByProxy(IMDBAPIClientTest.java:19)

Abhijit Sarkar
12 years ago
Reply to  mkyong

It was caused by RESTEasy. I figured it out as below:

res.getEntity(Movie.class, genericType); //works
res.getEntity(Movie.class); // fails as above

where res is a reference to ClientResponse and genericType is a subclass of Movie.