In this tutorial we will implement a Jersey client example with JSON support. The tools and technologies that I have used are;
- Eclipse 4.3.0
- JBoss AS 7.1.1.Final
- Maven 3.1.1
- JDK 1.7
Project Structure
Our project structure will look like below;
Dependencies
There are two dependencies to use Jersey client and JSON support
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.18.1</version>
</dependency>
- jersey-client dependency provides required jars for jersey client.
- jersey-json dependecy includes the jersey-json.jar which provides JSON support.
POJO Entity
We will simply use a Book entity which consists of 4 fields
public class BookEntity {
private int id;
private String title;
private String author;
private double price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Id : " + this.id + '\n');
stringBuilder.append("Title : " + this.title + '\n');
stringBuilder.append("Author : " + this.author + '\n');
stringBuilder.append("Price : " + this.price + '\n');
return stringBuilder.toString();
}
}
Client Configuration
To enable JSON support we have to turn JSONConfiguration.FEATURE_POJO_MAPPING
feature on for our jersey client. So we create our client with the following code;
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
Resource Class
Here are the interface and the implementation class of our resource
@Path("/book-service")
public interface BookResource {
@GET
@Path("/list")
@Produces({ MediaType.APPLICATION_JSON })
public Map<Integer, BookEntity> getBookList();
@GET
@Path("/find")
@Produces({ MediaType.APPLICATION_JSON })
public BookEntity findBook(@QueryParam("id") int id);
@POST
@Path("/create")
@Consumes("application/json")
@Produces("application/json")
public BookEntity createBook(BookEntity bookEntity);
}
public class DefaultBookResource implements BookResource {
private Map<Integer, BookEntity> list = new HashMap<Integer, BookEntity>();
private AtomicInteger idCounter = new AtomicInteger();
public DefaultBookResource() {
BookEntity bookEntity1 = new BookEntity();
bookEntity1.setId(idCounter.getAndIncrement());
bookEntity1.setAuthor("MargaretWeis");
bookEntity1.setTitle("TheSoulforge");
bookEntity1.setPrice(7.99);
BookEntity bookEntity2 = new BookEntity();
bookEntity2.setId(idCounter.getAndIncrement());
bookEntity2.setAuthor("Salvatore");
bookEntity2.setTitle("Exile");
bookEntity2.setPrice(9.99);
list.put(bookEntity1.getId(), bookEntity1);
list.put(bookEntity2.getId(), bookEntity2);
}
@Override
public Map<Integer, BookEntity> getBookList() {
return list;
}
@Override
public BookEntity findBook(int id) {
return list.get(id);
}
@Override
public BookEntity createBook(BookEntity bookEntity) {
bookEntity.setId(idCounter.getAndIncrement());
list.put(bookEntity.getId(), bookEntity);
return bookEntity;
}
}
-
Map<Integer, BookEntity> list
is a list that it will have two entities initially. -
AtomicInteger
provides to increment and decrement amotically an integer.
GET Request
As I mentioned earlier we have to create our Jersey client with JSON support, then we can start to make requests to available resources. I will first send a GET request to return a BookEntity if it exists.
public class JerseyClient {
public static void main(String[] args) {
// Create Jersey client
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
// GET request to findBook resource with a query parameter
String getBookURL = "http://localhost:8080/jersey-client-json-example/services/book-service/find";
WebResource webResourceGet = client.resource(getBookURL).queryParam("id", "1");
ClientResponse response = webResourceGet.get(ClientResponse.class);
BookEntity responseEntity = response.getEntity(BookEntity.class);
if (response.getStatus() != 200) {
throw new WebApplicationException();
}
System.out.println(responseEntity.toString());
}
}
Output;
Id : 1 Title : Exile Author : Salvatore Price : 9.99
Now lets see how we can get the list from response which contains BookEntities
// GET request to list resource
String getListURL = "http://localhost:8080/jersey-client-json-example/services/book-service/list";
webResourceGet = client.resource(getListURL);
response = webResourceGet.get(ClientResponse.class);
Map<Integer, BookEntity> list = webResourceGet.get(new GenericType<Map<Integer, BookEntity>>() {});
if (response.getStatus() != 200) {
throw new WebApplicationException();
}
for (Entry<Integer, BookEntity> entry : list.entrySet()) {
BookEntity bookEntity = entry.getValue();
System.out.println(bookEntity.toString());
}
GenericType
is the key object to get the list from the response.
Output will be ;
Id : 0 Title : TheSoulforge Author : MargaretWeis Price : 7.99 Id : 1 Title : Exile Author : Salvatore Price : 9.99
POST Request
Now we will create a BookEntity object to send it associated POST resource.
public class JerseyClient {
public static void main(String[] args) {
// Create Jersey client
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
// Jersey client POST example
BookEntity bookEntity = new BookEntity();
bookEntity.setTitle("LOTR");
bookEntity.setAuthor("Tolkien");
bookEntity.setPrice(12.99);
String postURL = "http://localhost:8080/jersey-client-json-example/services/book-service/create";
WebResource webResourcePost = client.resource(postURL);
response = webResourcePost.type("application/json").post(ClientResponse.class, bookEntity);
responseEntity = response.getEntity(BookEntity.class);
System.out.println(responseEntity.toString());
}
}
Finally our output will be;
Id : 2 Title : LOTR Author : Tolkien Price : 12.99
You can download the source code from here.
Comments powered by Disqus.