|
package com.renxing.Servletdemo;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class StringGZip extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//压缩数据实例
String data="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
System.out.println("压缩前的字节"+data.getBytes().length);
//小管道
ByteArrayOutputStream baos=new ByteArrayOutputStream();
//大管道
GZIPOutputStream out=new GZIPOutputStream(baos);
//大管道的数据写入小管道里
out.write(data.getBytes());
//大管道的关闭 内存刷新 确实的写入小管道里了。
out.close();
//小管道 里边的数据 通过 字节数组来获得
byte[] bytes=baos.toByteArray();
//然后定义 发送服务端的字节头
response.setHeader("content-length",bytes.length+"");
response.setHeader("content-encoding","gzip");
System.out.println("压缩后的字节:"+bytes.length);
//服务端对象response 写入到客户端屏幕上
response.getOutputStream().write(bytes);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
} |
|