Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 300
deamon Avatar asked Aug 07 '10 20:08

deamon


People also ask

What are the JAX-RS annotations?

Annotations in the JAX-RS API are used to provide meta-data around the web resource. A typical example is to use the @GET annotation with the @Path annotation to identify the method that should handle a GET request to the specified URI in the @Path annotation.

What is an implementation of JAX-RS specification?

While JAX-RS provides a faster way of developing web applications than servlets, the primary goal of JAX-RS is to build RESTful services. A server-side component API is defined in jaxrs-1.1 and jaxrs-2.0 to build REST applications. IBM® JAX-RS provides an implementation of the JAX-RS (JSR 311) specification.

Which of these are implementations of JAX-RS API?

JAX-RS is a standard defined in Java Specification Request 311 (JSR-311) and Jersey / RESTEasy are implementations of it.


2 Answers

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") 
like image 84
Adrian Petrescu Avatar answered Sep 23 '22 00:09

Adrian Petrescu


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()); 
like image 23
sfelber Avatar answered Sep 27 '22 00:09

sfelber