1.gzip 工具类
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
public class GZIPUtils {
private static final String ENCODING = "UTF-8";
/**
* 压缩
*
* @param data
* @return
* @throws Exception
*/
public static byte[] compress(byte[] data) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 压缩
GZIPOutputStream gos = new GZIPOutputStream(baos);
gos.write(data, 0, data.length);
gos.finish();
byte[] output = baos.toByteArray();
baos.flush();
baos.close();
return output;
}
/**
* @param response
* @throws ServletException
* @throws IOException
*/
public static void excute(HttpServletResponse response, String str)
throws ServletException, IOException {
byte[] data = str.toString().getBytes(ENCODING);
try {
byte[] output = compress(data);
// 设置Content-Encoding,这是关键点!
response.setHeader("Content-Encoding", "gzip");
response.setContentType("text/plain;charset=utf-8");
// 设置字符集
response.setCharacterEncoding(ENCODING);
// 设定输出流中内容长度
response.setContentLength(output.length);
OutputStream out = response.getOutputStream();
out.write(output);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.测试
@ResponseBody
@RequestMapping("/a")
public void a(HttpServletResponse response){
String str =
"流浪地球,相信你也看过,哈哈,你觉得怎么样呢,这不重要,重要的是可以压缩哦!一个现象就是,当数据不多时,压缩反而变大,你可以试试看哦";
System.out.println("原字符串:" + str);
System.out.println("原长度:" + str.length());
try {
GZIPUtils.excute(response,str);
}catch (Exception e){
e.printStackTrace();
}
}
3.测试结果
因为浏览器自带解析,只需要告诉浏览器格式为gizp。重点就是下面这句
response.setHeader("Content-Encoding", "gzip");
4.看结果
可以下载一个叫fiddler 的软件
如果不用压缩