May 24, 2015

Java REST Web Service with XML, JSON and HTML Response

When a client request some REST web service method, usually an HTTP GET request is sent, and within the header, the content-type parameter, that specifies which kind of response is expected and accepted. Here you can see how handle this situation, returning different kind of data based on the requested content-type.

If you don't know some term or technology used in the post, click here.

Let's use the same calculator from the Java REST Web Service tutorial and add the XML, HTML and JSON responses types for the sum method. It's simple, open the project and add this:

@GET
@Path("/sum")
@Produces(MediaType.TEXT_HTML)
public String SumHTML(@QueryParam("x") int x,@QueryParam("y") int y) {
 return "<html><body>HTML Response<br>Sum: " + x + "+" + y + "=" + (x+y) + "</body></html>";  
}  

@GET
@Path("/sum")
@Produces(MediaType.APPLICATION_JSON)
public String SumJSON(@QueryParam("x") int x,@QueryParam("y") int y) {
 return "{\"result\":"+(x+y)+"}";  
}  

@GET
@Path("/sum")
@Produces(MediaType.TEXT_XML)
public String SumXML(@QueryParam("x") int x,@QueryParam("y") int y) {
 return "<result>"+(x+y)+"</result>";  
}

As you can see, they are similar, just with the return string matching the MediaType. You can add support to the HTTP POST method too, replacing the @GET annotation by @POST. Although the APPLICATION_JSON can be chosen as MediaType, you can simply return a JSON string using the TEXT_PLAIN MediaType too!

Ok, and how can we test them? if you open directly on the browser like Firefox, IE or Chrome, they will request by default the HTML version, so the web service will return the HTML response. But if you edit the HTTP GET content-type header, then you can ask for the XML, TextPlain or JSON responses. The video below show how this can be done using the Firefox with its native debugger tool (F12):



Download
About the versions
  • Eclipse Java EE IDE for Web Developers Luna Service Release 1 (4.4.1)
  • Tomcat Server 8.0
  • JAX-RS Jersey version 2.15
  • Firefox 35.0.1

1 comment :