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

前端 未结 6 1203
鱼传尺愫
鱼传尺愫 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:18

    Using this answer as reference the solution to your question is to re-encode the JSON text as shown here:

    public void doFilter(...) {
        final CharResponseWrapper wrappedResponse =
                new CharResponseWrapper((HttpServletResponse) response);
    
        chain.doFilter(request, wrappedResponse);
    
        final String content = wrappedResponse.toString();
    
        final String type = wrappedResponse.getContentType();
        if (type != null && type.contains(MediaType.APPLICATION_JSON)) {
            // Re-encode the JSON response as UTF-8.
            response.setCharacterEncoding("UTF-8");
            final OutputStream out = response.getOutputStream();
            out.write(content.getBytes("UTF-8"));
            out.close();
        }
        else {
            // Otherwise just write it as-is.
            final PrintWriter out = response.getWriter();
            out.write(content);
            out.close();
        }
    }
    

提交回复
热议问题