是否爲GZIPInputStream格式(gzip壓縮格式)

判斷是否爲GZIPInputStream格式(gzip壓縮格式)

轉自 http://wingware.iteye.com/blog/1618561

Java代碼  收藏代碼
  1.               InputStream ips = null;  
  2. // 取前兩個字節  
  3. byte[] header = new byte[2];  
  4. if (isGzip()) {  
  5.     try {  
  6.         BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());  
  7.         bis.mark(2);  
  8.         int result = bis.read(header);  
  9.         // reset輸入流到開始位置  
  10.         bis.reset();  
  11.         // 判斷是否是GZIP格式  
  12.         int ss = (header[0] & 0xff) | ((header[1] & 0xff) << 8);  
  13.         if(result!=-1 && ss == GZIPInputStream.GZIP_MAGIC) {  
  14.             //System.out.println("爲數據壓縮格式...");  
  15.             ips= new GZIPInputStream(bis);  
  16.         } else {  
  17.             // 取前兩個字節  
  18.             ips= bis;  
  19.         }  
  20.     } catch (java.io.IOException e) {  
  21.         e.printStackTrace();  
  22.         ips = connection.getInputStream();  
  23.     }  
  24. else {  
  25.     ips = connection.getInputStream();  
  26. }  


判斷header中是否包含有gzip 
Java代碼  收藏代碼
  1. public boolean isGzip() {  
  2.         boolean gzip = false;  
  3.         for (String key : this.getHeaders().keySet()) {  
  4.             if (key.equalsIgnoreCase("Accept-Encoding") && this.getHeaders().get(key).contains("gzip")) {  
  5.                 gzip = true;  
  6.                 break;  
  7.             }  
  8.         }  
  9.         return gzip;  
  10.     }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章