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.


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:

public String SumHTML(@QueryParam("x") int x,@QueryParam("y") int y) {
 return "<html><body>HTML Response<br>Sum: " + x + "+" + y + "=" + (x+y) + "</body></html>";  

public String SumJSON(@QueryParam("x") int x,@QueryParam("y") int y) {
 return "{\"result\":"+(x+y)+"}";  

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):

About the versions
  • Tomcat Server 8.0
  • JAX-RS Jersey version 2.15
  • Firefox 35.0.1

1 comment :