/** * @author liweihan * @time 2016/12/23 11:56 * @description 返回JSON格式!若是含有<br/> ,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代碼!html