筆記如下
//response.getOutputStream().print("hahaha");
String data="alsjdalskjdlasjd123123123123123123123123dfgfvsdvdsgsdgsdgsgalsjdalskjdlasjd123"
+ "123123123123123123123dfgfvsdvdsgsdgsdgsgalsjdalskjdlasjd1231231231231adasdasdasd"
+ "23123123123dfgfvsdvdsgsdgsdgsg23123123123dfgfvsdvdsgsdgsdgsg23123123123dfgfvsdvg"
+ "sdgsg23123123123dfgfvsdvdsgsdgsdgsgsdgsg23123123123dfgfvsdvdsgsdgsdgsg";
byte[] b = data.getBytes();
System.out.println("壓縮前" + b.length);
//底層流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//采用gzip壓縮
//這里壓縮的時候輸出一個輸出流,這里的輸出流是一個底層流
GZIPOutputStream gout = new GZIPOutputStream(baos);
gout.write(b);
//由于數據是寫到底層流baos中的,gout 默認有緩沖區的.
gout.close();//close()確保可以寫到boas中去
b = baos.toByteArray();
System.out.println("壓縮后" + b.length);
//告訴瀏覽器 需要 解壓數據 --- 通過http響應頭
response.setHeader("content-encoding", "gzip");
response.setContentLength(b.length);//數組的長度
演示:
4.png