How To Create A Rest Client For GET Request

Create a Rest Client for a GET request is very simple.  We will create a simple Java application which will call a REST service with GET method and return a object in JSON format.  Then the object is printed.

JerseyClient.java

Steps

  1.  Create a webresource which maps to the REST url
  2. Create a response object which accepts application/json.  get method gets the response.
  3. Retreive the Book object from the response and print it.
package com.freetipscentral;

import com.freetipscentral.domain.Book;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClient {

  public static void main(String args[]) {
    Client client = new Client();
    WebResource resource = client.resource("http://localhost:8080/RestWebProject/rest/books/1");
    
    ClientResponse response = resource.accept("application/json")
                .get(ClientResponse.class);
    
    Book book1 = response.getEntity(Book.class);
    System.out.println(book1);
  }

}

JerseyRestServiceWithJSON.java

This is a simple class which returns a Book object when invoked with a book id.

package com.freetipscentral;
 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
 
import com.freetipscentral.domain.Book;
 
@Path("/books")
public class JerseyRestServiceWithJSON {
 
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Path("{bookId}")
  public Book getBook(@Context HttpHeaders headers, @PathParam("bookId") int bookId) {
    Book book = null;
    Book book1 = new Book("Harry Potter",1);
    Book book2 = new Book("Harry Potter",2);
 
    if(bookId == 1) {
      book = book1;
    } else {
      book = book2;
    }
    return book;
  }
}

Book.java

package com.freetipscentral.domain;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Book {
  String name;
  int serialNumber;
 
  public Book() {}
 
  public Book(String name, int serialNumber) {
    this.name = name;
    this.serialNumber = serialNumber;
  }
 
  public String getName() {
    return name;
  }
 
  public void setName(String name) {
    this.name = name;
  }
 
  public int getSerialNumber() {
    return serialNumber;
  }
 
  public void setSerialNumber(int serialNumber) {
    this.serialNumber = serialNumber;
  }
 
  public String toString() {
    return serialNumber + " "  + name;
  }	
}

Here is the output

1 Harry Potter