Servlet不能设置编码,设置编码无效!?

 我设置了这些东西但是
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=UTF-8");
代码完无效
response.setCharacterEncoding("utf-8");
    response.setContentType(harEntry.response.content.mimeType);
    response.setStatus(harEntry.response.status);
    for (HarHeader header : harEntry.response.headers) {
        response.addHeader(header.name, header.value);
    }
    PrintWriter ss = response.getWriter();
    ss.write(remoteContent);
    ss.close();
} else {
    remoteContentBin = EntityUtils.toByteArray(remoteEntity);
    response.getOutputStream().write(remoteContentBin);
}

if (response.getContentType() == null || "".equals(response.getContentType())) {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=UTF-8");
    response.addHeader("Content-Type", "application/json;charset=UTF-8");
原因是Response只要有访问就打开了流,只要打开了流,就不能设置编码了
如  response.getXXXX,response.setXXXXX 都会打开流!!

解决:在所有访问前提前设置编码:
public void doMock(HttpServletRequest request, HttpServletResponse response, String servername) {
    try {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
.....

发布了47 篇原创文章 · 获赞 9 · 访问量 15万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览