Friday, June 1, 2012

JAX-RS Jersey Client Example With Post

Let's take example of the operateXMLNumbers restful service, which excepts data in XML format and also returns data in XML format. This service is simple and add two numbers and returns the data.
Following show's the service method written using Jersey. Notice that the parameter is mapped object type
The Full code can be found at google code.

Service Method

 public MathResponse addTwoXMLNumbers(MathRequest rq) {
     String numa = rq.getOperandA().toString();
     String numb = rq.getOperandB().toString();
     String operator1 = rq.getOperationTypeNew();
     Integer result = doCalculateCoreLogic(operator1, numa, numb);
     MathResponse rs = new MathResponse();
     return rs;

   private static void callTwoXMLNumbers() {
 Client client = Client.create();
 WebResource webResource = client.resource("http://localhost:8080/MyJRS2/rest/");
 MathRequest rq = new ObjectFactory().createMathRequest();
 rq.setOperandA(new BigInteger("100"));
 rq.setOperandB(new BigInteger("100"));
  MathResponse response = webResource.path("calculate").path("operateXMLNumbers")
        .post(MathResponse.class, rq);

 System.out.format("Output from Server .... Result = %s \n" ,response.getResult() );
Using WebResource we are specifying that the mediatype is application/xml and mathod is the post method. We are specifying that, upon posting rq data we are expecting MathResponse type data back from service. All the marshalling and unmarshalling is taken care by JAXB, and we can simply play with objects.

No comments :

Post a Comment