筆記如下
//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);
//由于數(shù)據(jù)是寫到底層流baos中的,gout 默認(rèn)有緩沖區(qū)的.
gout.close();//close()確贝胍耄可以寫到boas中去
b = baos.toByteArray();
System.out.println("壓縮后" + b.length);
//告訴瀏覽器 需要 解壓數(shù)據(jù) --- 通過http響應(yīng)頭
response.setHeader("content-encoding", "gzip");
response.setContentLength(b.length);//數(shù)組的長度
演示:
4.png