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.


  1. "Nice and good article.. it is very useful for me to learn and understand easily.. thanks for sharing your valuable information and time.. please keep updating.php jobs in hyderabad.

  2. You can shop online for precisely what you need for your little puppy and have it transported appropriate to your home yet.custom cubs jersey

  3. They exemplify the immense versatility that this structure possesses, but also represents the fundamental purpose of the Jersey Barrier, and that is to establish and maintain public custom t-shirts

  4. Men would truly appear to be beguiling in muscle shirts. Regularly the young ladies are interested with the circumstance shirts. cheap custom t shirts

  5. The Venetian Las Vegas - JTM Hub
    Located 군산 출장마사지 in Las Vegas, the 경주 출장샵 Venetian is located in the 광주광역 출장마사지 heart of the strip, 공주 출장마사지 steps from The Cosmopolitan 동두천 출장안마 and the Venetian. The Venetian, known in Las Vegas as