Java 如何使用 JAX-RS 设置字符集?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3431996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set the charset with JAX-RS?
提问by deamon
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.
如何使用 JAX-RS 设置字符集?我试过,@Produces("text/html; charset=UTF-8")
但被忽略了,只text/html
与 HTTP 标头一起发送。我想在 MessageBodyWriter 中设置字符集,但不想通过自己通过反射分析 @Produces 注释来提取媒体类型。
采纳答案by Adrian Petrescu
As Daemon pointed out in a comment, the latest versions of JAX-RS (including the stable version as of September 2012) now dosupport the @Produces
syntax. So you can just use:
正如 Daemon 在评论中指出的那样,最新版本的 JAX-RS(包括截至 2012 年 9 月的稳定版本)现在确实支持该@Produces
语法。所以你可以使用:
@Produces("text/html; charset=UTF-8")
回答by Bryant Luk
If you want to do this in a JAX-RS implementation neutral way, you may be able to reset the Content-Type in the MessageBodyWriter. Something like:
如果您想以 JAX-RS 实现中立的方式执行此操作,您可以重置 MessageBodyWriter 中的 Content-Type。就像是:
public void writeTo(Object obj,
Class<?> cls,
Type type,
Annotation[] annotations,
MediaType mt,
MultivaluedMap<String, Object> responseHttpHeaders,
OutputStream stream) throws IOException {
responseHttpHeaders.putSingle(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, mt.toString() + ";charset=UTF-8");
}
If you have different character sets besides UTF-8 per resource method, you may want to create a custom annotation and add it to each resource method. Then, try to use the annotations parameter in the writeTo() method.
如果每个资源方法除了 UTF-8 之外还有不同的字符集,您可能需要创建自定义注释并将其添加到每个资源方法。然后,尝试使用 writeTo() 方法中的 annotations 参数。
Just FYI, Apache Winksupports the usage of charset and other attributes on media types. I hope that future JAX-RS spec revisions makes this easier.
仅供参考,Apache Wink支持在媒体类型上使用字符集和其他属性。我希望未来的 JAX-RS 规范修订能让这更容易。
回答by SMougenot
It is also possible to use ResponseBuilder.header(...) method to set the content type with the charset. See below for a code sample (using JAX-RS 1.1.1, CXF 2.3.1).
也可以使用 ResponseBuilder.header(...) 方法来设置带有字符集的内容类型。请参阅下面的代码示例(使用 JAX-RS 1.1.1、CXF 2.3.1)。
final Response myResponse = Response.status(Response.Status.BAD_REQUEST)
.entity("La requête n'est pas correcte.\n ...")
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN+"; charset=ISO-8859-15" )
.build();
回答by stviper
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:
只是为了保持最新状态。不确定旧版本的 Jersey 是否支持此功能,但如果您决定使用 ResponseBuilder.header(...) 方法,您可以使用 MediaType 方法withCharset()。像这样:
return Response.status(Status.OK)
.entity(result)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_TYPE.withCharset("utf-8"))
.build());
回答by To Kra
First setup @Produces
annotation on your resource class methods.
首先@Produces
在您的资源类方法上设置注释。
Then in MessageBodyWriter
of your returned type, you can do this in writeTo()
method:
然后在MessageBodyWriter
您返回的类型中,您可以在writeTo()
方法中执行此操作:
response.setContentType(mediaType.toString);
Remark: You can inject response
in your writer
by:
备注:你可以注入response
你的writer
是:
@Context
protected HttpServletResponse response;
回答by Giannis
What I do is to get an instance of the servlet response object:
我所做的是获取 servlet 响应对象的实例:
protected @Context HttpServletResponse response;
And then set the character encoding to utf-8:
然后将字符编码设置为utf-8:
response.setCharacterEncoding("utf-8");
That works for me.
这对我行得通。
回答by lujop
If using RESTEasy you can register an Inteceptor:
如果使用 RESTEasy,您可以注册一个拦截器:
import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import org.jboss.resteasy.core.ResourceMethodInvoker;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.Provider;
@Provider
@ServerInterceptor
public class ContentTypeSetter implements PreProcessInterceptor {
@Override
public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker resourceMethodInvoker) throws Failure, WebApplicationException {
request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, "*/*; charset=UTF-8");
return null;
}
}
Note: If you manually set a @Produces it overrides the ContentType set by this interceptor. If you do that, set the charset in @Produces
注意:如果您手动设置 @Produces,它会覆盖此拦截器设置的 ContentType。如果这样做,请在@Produces 中设置字符集