java setcontenttype_response.setContentType()简单了解

/**

* @author liweihan

* @time 2016/12/23 11:56

* @description  返回JSON格式!如果含有
 ,text/html就显示变化了!

* @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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值