本文共 1372 字,大约阅读时间需要 4 分钟。
import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.PrintWriter;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 Dmo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "bbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; System.out.println("压缩前" + data.length()); // 以下代码完成将String类型压缩到byte[]中 ByteArrayOutputStream bout = new ByteArrayOutputStream(); GZIPOutputStream gout = new GZIPOutputStream(bout); gout.write(data.getBytes()); gout.flush(); gout.close(); // 取出压缩后的数据 byte[] buf = bout.toByteArray(); System.out.println("压缩后" + buf.length); // 将压缩后的数据输出到浏览器 response.setHeader("content-encoding", "gzip"); response.setHeader("content-length", buf.length + ""); // 服务端以字节方式输出 response.getOutputStream().write(buf); }}
访问:
转载于:https://blog.51cto.com/357712148/2104330