How to set the charset with JAX-RS?

后端 未结 7 1103
时光说笑
时光说笑 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 using RESTEasy you can register an Inteceptor:

    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

提交回复
热议问题