Java Client To Get Xml Response From GET Method

Getting response from a REST service from a POST request, using a Java client is very simple as we saw in this example.  In this tutorial we will see how to get a response from GET method from a REST method.  We will again use a Java client for this.

Here is the Service class

RestXMLService.java

package com.freetipscentral;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.freetipscentral.domain.Book;

@Path("/getXML")
public class RestXMLService {

  @Produces(MediaType.APPLICATION_XML)
  @GET
  public Book getBookAsXML() {
    
    Book book1 = new Book("Head First Java", 1);
    
    return book1;
  }
}

Domain class.

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;
  }	
}

REST Client

JerseyRestGetClient.java

package com.freetipscentral;

import javax.ws.rs.core.MediaType;

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

public class JerseyRestGetClient {
  public static void main(String args[]) {
    
    Client client = Client.create();
    WebResource resource = client.resource("http://localhost:8080/RestWebService/rest/getXML");
    
    Book response =resource.accept(MediaType.APPLICATION_XML)
    .get(Book.class);
    
    System.out.println(response);
  }
}

The jar files required are as follows

  • genson-1.3.jar
  • jersey-bundle-1.9.jar
  • jersey-core-1.8.jar

Here is the output

 

1 Head First Java

2 thoughts to “Java Client To Get Xml Response From GET Method”

  1. I see your blog is in the same niche like my site.

    Do you allow guest posting? I can write high quality posts for you.

    Let me know if you are interested.

Comments are closed.