java setcontenttype_response.setContentType()简单了解

java setcontenttype_response.setContentType()简单了解authorliweih time2016 12 2311 56 description 返回 JSON 格式 如果含有 text html 就显示变化了 paramrequest paramrespons paramresult paramcallBac 参考 http blog sina com cn s blog a03d702

/

* @author liweihan

* @time 2016/12/23 11:56

* @param request

* @param response

* @param result

* @param callBack

* 参考:http://blog.sina.com.cn/s/blog_a03d702f010143tw.html

*  text/html           HTML

text/plain          TXT

text/xml             XML

application/json           json字符串

text/html的意思是将文件的content-type设置为text/html的形式,浏览器在获取到这种文件时会自动调用html的解析器对文件进行相应的处理。

text/plain的意思是将文件设置为纯文本的形式,浏览器在获取到这种文件时并不会对其进行处理。

*/

public void printJsonAutoEncodeNoCache(HttpServletRequest request, HttpServletResponse response, String result, String callBack) {

if (StringUtils.isNotBlank(callBack)) {

result = new StringBuffer(ToolUtil.filterHtml(callBack)).append(“(“).append(result).append(“)”).toString();

}

byte[] outBytes;

try {

String encoding = “gbk”;

if (StringUtils.isNotBlank(request.getParameter(“encoding”))) {

encoding = request.getParameter(“encoding”);

}

if (“gbk”.equalsIgnoreCase(encoding.trim())) {

response.setContentType(“application/json; charset=GBK”);

outBytes = result.getBytes(“gbk”);

} else {

response.setContentType(“application/json; charset=UTF-8”);

outBytes = result.getBytes(“utf-8”);

}

response.setHeader(“Pragma”, “No-cache”);

response.setHeader(“Cache-Control”, “no-cache”);

response.setDateHeader(“Expires”, 0);

response.getOutputStream().write(outBytes);

//            response.flushBuffer();

/

* 2016-07-11-han-add – explain:

* response.flushBuffer():Forces any content in the buffer to be written to the client.

* A call to this method automatically commits the response, meaning the status code and headers will be written.

*

* java.lang.Object

extended byjava.io.OutputStream

extended byjavax.servlet.ServletOutputStream

OutputStream.flush(): 刷新此输出流并强制写出所有缓冲的输出字节。

OutputStream.close():关闭此输出流并释放与此流有关的所有系统资源。

*/

response.getOutputStream().flush();

response.flushBuffer();

response.getOutputStream().close();

} catch (IOException e) {

logger.error(” ====== print result error”, e);

}

}

注意一下,如果我们要返回JSON格式的数据,尽量设置response.setContentType()为application/json,这样可以防止运营商劫持!然后在我们的返回结果中加一些广告的JS代码!

1364462e16b768545d1699267729463a.png

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/207950.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月19日 下午12:43
下一篇 2026年3月19日 下午12:43


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号