users@jersey.java.net

Re: [Jersey] Impossibility to set charset - Is it a bug?

From: Paul Sandoz <Paul.Sandoz_at_oracle.com>
Date: Mon, 9 Aug 2010 07:49:36 +0200

On Aug 8, 2010, at 12:49 PM, Christian Helmbold wrote:

> Hello,
>
> shouldn't it be possible to specify the charset with @Produces("text/
> html;
> charset="UTF-8")? It doesn't work, Jersey still sends "Content-Type:
> text/html"
> without the charset parameter.
>

What version of Jersey are you using?

Where are you declaring the @Produces?

It should work if declaring on the resource method/class.


>
> As a workaround a tried to set the Content-Type header by modifying
> the
> httpHeaders map in the writeTo method of my MessageBodyWriter. But
> then I've got
> only the charset as the content type without the media type. I tried
> this:
>
> httpHeaders.add("Content-Type", "; charset=UTF-8"); and
> httpHeaders.add("Content-Type", "charset=UTF-8");
>
> I've thought that I could connect multiple values of a header this
> way.
>
> The only workaround I've found is this:
>
> httpHeaders.putSingle("Content-Type", mediaType + "; charset=UTF-8");
>

See MediaType, you need to add "charset" as a parameter to the media
type, then you can add the media type instance rather than the string.

For example since the media type is already available you can do:

   httpHeaders.putSingle("Content-Type", new MediaType(oldMediaType,
Collections.singletonMap("charset", "UTF-8"));

Paul.

[1] https://jsr311.dev.java.net/nonav/releases/1.1/javax/ws/rs/core/MediaType.html