Change ContentType or CharacterEncoding in Java Filter ONLY IF ContentType === JSON

前端 未结 6 1204
鱼传尺愫
鱼传尺愫 2021-01-01 04:32

I\'m trying to ensure that all JSON responses from a Jersey based java application have a UTF-8 character encoding parameter appended to their ContentType header.

So

6条回答
  •  醉酒成梦
    2021-01-01 05:07

    Had success using a ContainerResponseFilter:

    public class ContentTypeEncodingFilter implements ContainerResponseFilter {
        @Override
        public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
            String contentType = responseContext.getHeaderString(HttpHeaders.CONTENT_TYPE);
            if (contentType == null) {
                return;
            }
            ContentType parsedType = ContentType.parse(contentType);
            if (parsedType.getCharset() != null) {
                return;
            }
            ContentType encodedType = parsedType.withCharset(StandardCharsets.UTF_8);
            responseContext.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, encodedType.toString());
        }
    }
    

提交回复
热议问题