要點:
1.new一個GZIPOutputStream,而GZIPOutputStream裏面需要包一個流,最好是包一個內存流ByteArrayOutputStream,因爲內存流不需要知道長度而且其長度可以變化。
2.輸出壓縮數據時,必須設置響應頭
resp.setHeader(“Content-Encoding”, “gzip” );
public class GzipServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
String str="dklkewi湖南城市學院湖南城市學院湖南城市學院湖南城市學院湖南城市學院湖南城市學院w224242424242424444444444422424241dfdfdffddffdfdds244224242424242424444444444422424241dfdfdffiow湖南城市學院esdkkewwe,m";
byte src[] = str.getBytes("UTF-8");
System.out.println("壓縮前的長度:"+src.length);
ByteArrayOutputStream bout = new ByteArrayOutputStream();//內存流
GZIPOutputStream gzipOut = new GZIPOutputStream( bout );
gzipOut.write(src);//把src壓縮到 bout中
gzipOut.close();//刷緩存
byte dest[] = bout.toByteArray();//把源數據src壓縮成目標數據dest
System.out.println("壓縮後的長度:"+dest.length);
resp.setContentType("text/html;charset=utf-8");
//輸出壓縮數據時,必須設置響應頭
resp.setHeader("Content-Encoding", "gzip" );
OutputStream out = resp.getOutputStream();
out.write(dest);
}
}
注意:若需要壓縮的str長度太短可能會出現壓縮後的長度大於壓縮前的長度這種情況,這是因爲壓縮本身需要消耗,只有需壓縮的str夠長才能體現
壓縮的作用。