How to set the charset with JAX-RS?

How can I set the charset with JAX-RS? I've tried @Produces("text/html; charset=UTF-8") but that was ignored and only text/html was send with the HTTP header. I want to set the charset within a MessageBodyWriter, but don't want to extract the media type by analysing the @Produces annotation via reflection by myself.


Solution 1:

As Daemon pointed out in a comment, the latest versions of JAX-RS (including the stable version as of September 2012) now do support the @Produces syntax. So you can just use:

@Produces("text/html; charset=UTF-8")

Solution 2:

Just to keep it up to date. Not sure whether this was supported in older versions of Jersey, but definitely if you decide to use ResponseBuilder.header(...) method you can use MediaType method withCharset(). Like this:

return Response.status(Status.OK)
         .entity(result)
         .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_TYPE.withCharset("utf-8"))
         .build());