I am developing a web service using the JAX-RS API with Jersey 1.17 as my implementation.
I want clients to have a choice between the JSON and XML that they specify using the AcceptHTTP header . I want JSON to be the default when the client does not include the header Acceptin the request. I tried to achieve this by posting MediaType.APPLICATION_JSONup MediaType.APPLICATION_XMLin the annotation Produces.
This seems to work in normal situations:
$ curl 'http://localhost:8080/webservice/Bob'
{"text":"Hello, Bob"}
$ curl -H'Accept: application/json' 'http://localhost:8080/webservice/Bob'
{"text":"Hello, Bob"}
$ curl -H'Accept: application/xml' 'http://localhost:8080/webservice/Bob'
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Greeting text="Hello, Bob"/>
But if I drop WebApplicationExceptionfrom the constructor of my resource class, the default media response type will match the XML:
$ curl 'http://localhost:8080/webservice/Vader'
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Error message="Illegal name"/>
If the client includes a header Accept, the media type is correct:
$ curl -H'Accept: application/json' 'http://localhost:8080/webservice/Vader'
{"message":"Illegal name"}
, ?
( GitHub):
package org.example.errorhandling;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.example.errorhandling.repr.Error;
import org.example.errorhandling.repr.Greeting;
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Path("/{name}")
public class Greeter {
private final String name;
public Greeter(@PathParam("name") String name) {
if ("Vader".equals(name)) {
Error error = new Error();
error.message = "Illegal name";
Response errorResponse = Response.status(Status.BAD_REQUEST).entity(error).build();
throw new WebApplicationException(errorResponse);
} else {
this.name = name;
}
}
@GET
public Response greet() {
Greeting greeting = new Greeting();
greeting.text = "Hello, " + name;
return Response.ok(greeting).build();
}
}