Reputation: 1439
Using JAXB for implementing a REST-Webservice, we have several methods that are producing output.
The class that contains all of these methods is annotated with @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
. If a request goes the happy-path (no errors occur), we return the POJO's in our methods and JAXB dynamically marshalls these objects into application/xml
or application/json
, as the client requested it via Accept: application/xxx;
in the request header.
My question is how to get the requested content type, because if an error occurs, we are throwing a WebApplicationException
with a response which should contain a custom error message formatted into the requested content type.
Upvotes: 3
Views: 4245
Reputation: 209112
Inject with @HeaderParam("Accept")
public Response doSomething(@HeaderParam("Accept") String accept) {
// you may need to parse it as the value is not always as
// simple as application/json
}
Inject HttpHeaders
, where you have a couple options
public Response doSomething(@Context HttpHeaders headers) {
String accept = headers.getHeaderString(HttpHeaders.ACCEPT);
List<MediaType> acceptableType = headers.getAcceptableMediaTypes();
}
Upvotes: 7