「轉載請說明出處:http://blog.csdn.net/kepoon/article/details/7482096」
gzip是GNUzip的縮寫,它是一個GNU自由軟件的文件壓縮程序。
HTTP協(xié)議上的GZIP編碼是一種用來改進WEB應用程序性能的技術。一般服務器中都安裝有這個功能模塊的,服務器端不需做改動。
當瀏覽器支持gzip 格式的時候, 服務器端會傳輸gzip格式的數(shù)據(jù)。
從Http 技術細節(jié)上講,就是 http request 頭中 有 "Accept-Encoding", "gzip" ,response 中就有返回頭Content-Encoding=gzip 。
我們現(xiàn)在從瀏覽器上訪問玩啥網(wǎng)站都是gzip格式傳輸?shù)摹?/p>
但是我們現(xiàn)在android 客戶端,沒有用gzip 格式訪問。
同樣的的道理,我們可以在android 客戶端 request 頭中加入 "Accept-Encoding", "gzip" ,來讓服務器傳送gzip 數(shù)據(jù)。
具體代碼如下。
private String getJsonStringFromGZIP(HttpResponse response) { String jsonString = null; try { InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); bis.mark(2); // 取前兩個字節(jié) byte[] header = new byte[2]; int result = bis.read(header); // reset輸入流到開始位置 bis.reset(); // 判斷是否是GZIP格式 int headerData = getShort(header); // Gzip 流 的前兩個字節(jié)是 0x1f8b if (result != -1 && headerData == 0x1f8b) { LogUtil.d("HttpTask", " use GZIPInputStream "); is = new GZIPInputStream(bis); } else { LogUtil.d("HttpTask", " not use GZIPInputStream"); is = bis; } InputStreamReader reader = new InputStreamReader(is, "utf-8"); char[] data = new char[100]; int readSize; StringBuffer sb = new StringBuffer(); while ((readSize = reader.read(data)) > 0) { sb.append(data, 0, readSize); } jsonString = sb.toString(); bis.close(); reader.close(); } catch (Exception e) { LogUtil.e("HttpTask", e.toString(),e); } LogUtil.d("HttpTask", "getJsonStringFromGZIP net output : " + jsonString ); return jsonString; } private int getShort(byte[] data) { return (int)((data[0]<<8) | data[1]&0xFF); }
參考 ,注意實際使用中,我發(fā)現(xiàn)gzip 流前兩個字節(jié)是0x1e8b ,不是0x1f8b .后來檢查一下code ,代碼處理錯誤,加上第二個字節(jié)的時候需 &0xFF
0x1f8b 可參考標準 http://www.gzip.org/zlib/rfc-gzip.html#file-format