Gzip压缩技术
为减少网络数据传输,从而减少传输时长,增加用户体验,可采用Gzip压缩技术进行优化。
大部分浏览器是支持Gzip压缩技术的。
http的请求头 Accept-Encoding:gzip, deflate 就表示这次请求可以接受Gzip压缩后的数据。
1、HttpServlet开启Gzip压缩:
public void resultGzipJsonp(HttpServletResponse response,JSONObject json) {
try {
response.setHeader("Content-Encoding", "gzip");//设置gzip压缩格式
GZIPOutputStream gzipout = new GZIPOutputStream(response.getOutputStream(), 1024);
gzipout.write(json.toString().getBytes("UTF-8"));
gzipout.flush();
gzipout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2、SpringBoot开启Gzip压缩
server.compression.enabled=true
server.compression.mime-types=application/javascript,text/css,application/json,application/xml,text/html,text/xml,text/plain
压缩前:
压缩后:
可以看到压缩前后大小将近压缩3倍多。