Basti Funck
Basti Funck

Reputation: 1439

How to get the requested contenttype of a REST-Request?

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

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209112

You could...

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
}

You could...

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

Related Questions