users@jersey.java.net

[Jersey] Content-Type not set when throwing WebApplicationException

From: Mikael Ståldal <mikael.staldal_at_appearnetworks.com>
Date: Wed, 24 Sep 2014 17:29:23 +0200

I have a custom MessageBodyWriter to serialize objects into JSON, this
class is annotated with @Provider @Produces(MediaType.APPLICATION_JSON) and
registered in the Jersey server container.

When I throw a WebApplicationException like this:

throw new
WebApplicationException(Response.status(Response.Status.NOT_FOUND).
entity(new ErrorMessage("not found")).build());

then my MessageBodyWriter is invoked and serialize the ErrorMessage class
into JSON, which I see in the response body. So far so good. However, the
HTTP response have no Content-Type header.

If I throw the WebApplicationException like this instead:

throw new
WebApplicationException(Response.status(Response.Status.NOT_FOUND).
type(MediaType(MediaType.APPLICATION_JSON_TYPE).entity(new
ErrorMessage("not found")).build());

then the HTTP response will have have Content-Type header as expected.

Isn't Jersey supposed to set Content-Type from the @Produces annotation on
the MessageBodyWriter (if not set in the Response object)?

When I return a POJO from a resource method, the Content-Type response
header is properly set.

(Using Jersey 2.12.)

-- 
Mikael Ståldal
Chief Software Architect
*Appear*
Phone: +46 8 545 91 572
Email: mikael.staldal_at_appearnetworks.com