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
MathRequest.
The Full code can be found at google code.

Service Method

        @POST
 @Path("operateXMLNumbers")
 @Produces(MediaType.APPLICATION_XML)
 @Consumes(MediaType.APPLICATION_XML)
 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();
     rs.setMathOperationRQ(rq);
     rs.setResult(result);
     return rs;
 }


Client
   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"));
 rq.setOperationTypeNew("add");
  MathResponse response = webResource.path("calculate").path("operateXMLNumbers")
        .type(MediaType.APPLICATION_XML)
        .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