Thursday, August 29, 2013

REST JAX-RS 2.0 Jersey Client API

Hello, everyone!

This post will show an example of how can you use the new JAX-RS 2.0 Client API from Jersey.

For this project we will use JBOSS AS 7.1 (Port 8082) with Maven and our plan is to consume a REST service asking for an "Order" passing an id as a parameter.

So let's get started!

This first line of code will give you a new instance of the client.
Client orderClient = ClientBuilder.newClient();

The next step is to make a GET request to a WebTarget (A resource target identified by the resource URI) asking for the "Order".
         WebTarget target  = orderClient
         Response response = target
                                .resolveTemplate("id", 1) // Resolves the {id} template
Note that you also could use another http method like post(), put() or any other you choose. After that you just have to check if the response is OK (Status code 200) and read the entity, if you are trying to read a List<Order> it will be a bit tricky  and I will be writing a post just for this case (The code for this is under github, check that out).
  if(response.getStatus() == Status.OK.getStatusCode()){
   Order order = (Order) response.readEntity(Order.class);
   System.out.println("Id: " + order.getId());
   System.out.println("Name: " + order.getName());
   System.out.println("Price: " + order.getPrice());
   System.out.println(response.getStatus() + " " + response.getStatusInfo());
So if the service is running and everything is ok, you will get the Order correctly from the server and it will be printed in the console.

The full example with maven configuration and code is under repository, be free to fork it. There you also will find the REST service and the client implementation.

See you next time! Thanks.