Gzip也是android客戶端支持的方式,官網解釋:GZIPInputStream此類類是用來讀取在GZIP格式存儲的數據,從底層的流進它的緩沖區讀取和解壓GZIP數據。

 

 InputStreamis=...
 GZIPInputStream zis =newGZIPInputStream(newBufferedInputStream(is));
 try{
     // Reading from 'zis' gets you the uncompressed bytes...
     processStream(zis);
 }finally{
     zis.close();
 }
1, 工具類:測試客戶端是否支持GZIP編碼壓縮方式 & 獲得支持GZIP的PrintWriter對象  
  
package freebsd;  
  
import java.io.IOException;  
import java.io.PrintWriter;  
import java.util.zip.GZIPOutputStream;  
  
import javax.servlet.ServletOutputStream;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
  
public class Utilities {  
/* 
* 測試客戶端瀏覽器是否支持gzip的編碼方式 
*/  
public static boolean isSurpported(HttpServletRequest request)  
{  
   String encodingString = request.getHeader("Accept-Encoding");  
   return (encodingString!=null) && (encodingString.indexOf("gzip")!=-1);  
}  
/* 
* 取得一個壓縮的PrintWriter 
*/  
public static PrintWriter getWriter(HttpServletResponse response) throws IOException  
{  
   ServletOutputStream sos = response.getOutputStream();  
   GZIPOutputStream gzipos = new GZIPOutputStream(sos);  
   return new PrintWriter(gzipos);  
}  
  
}  
2,Servlet類,產生一個長字符串,然後在html頁面中請求該servlet:  
  
import freebsd.*;  
  
import java.io.IOException;  
import java.io.PrintWriter;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
/** 
* Servlet implementation class ServletGzip 
*/  
public class ServletGzip extends HttpServlet {  
private static final long serialVersionUID = 1L;  
         
    /** 
     * @see HttpServlet#HttpServlet() 
     */  
    public ServletGzip() {  
        super();  
        // TODO Auto-generated constructor stub  
    }  
  
/** 
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
*/  
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
   doPost(request, response);  
}  
  
/** 
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
*/  
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
   response.setContentType("text/html");  
   response.setStatus(response.SC_OK);  
   PrintWriter out;  
   if(Utilities.isSurpported(request))  
   {  
    out = Utilities.getWriter(response);  
  
   //協議: 通知客戶端使用gzip這種壓縮方式而不是其它的,如compress  
   response.setHeader("Content-Encoding", "gzip");  
   }else {  
    out = response.getWriter();  
   }  
  StringBuilder sBuilder = new StringBuilder();  
   for(int i=0; i!=5000; ++i)  
   {  
    sBuilder.append("Printing the long string... ...!");  
   }  
   out.println(sBuilder);  
out.close();  
}  
}  
創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()