How to set the charset with JAX-RS?

后端 未结 7 1082
时光说笑
时光说笑 2020-12-08 09:30

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 th

7条回答
  •  囚心锁ツ
    2020-12-08 09:52

    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:

    public void writeTo(Object obj,
                        Class cls,
                        Type type,
                        Annotation[] annotations,
                        MediaType mt,
                        MultivaluedMap 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.

    Just FYI, Apache Wink supports the usage of charset and other attributes on media types. I hope that future JAX-RS spec revisions makes this easier.

提交回复
热议问题