歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發中網絡請求的壓縮 ── GZip的使用

Android開發中網絡請求的壓縮 ── GZip的使用

日期:2017/3/1 10:24:25   编辑:Linux編程

gzip是GNUzip的縮寫,它是一個GNU自由軟件的文件壓縮程序。

HTTP協議上的GZIP編碼是一種用來改進WEB應用程序性能的技術。一般服務器中都安裝有這個功能模塊的,服務器端不需做改動。

當浏覽器支持gzip 格式的時候, 服務器端會傳輸gzip格式的數據。

從Http 技術細節上講,就是 http request 頭中 有 "Accept-Encoding", "gzip" ,response 中就有返回頭Content-Encoding=gzip 。

我們現在從浏覽器上訪問玩啥網站都是gzip格式傳輸的。

但是我們現在Android 客戶端,沒有用gzip 格式訪問。

同樣的的道理,我們可以在android 客戶端 request 頭中加入 "Accept-Encoding", "gzip" ,來讓服務器傳送gzip 數據。

具體代碼如下。

private String getJsonStringFromGZIP(HttpResponse response) {
String jsonString = null;
try {
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
bis.mark(2);
// 取前兩個字節
byte[] header = new byte[2];
int result = bis.read(header);
// reset輸入流到開始位置
bis.reset();
// 判斷是否是GZIP格式
int headerData = getShort(header);
// Gzip 流 的前兩個字節是 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);
}

參考 ,注意實際使用中,我發現gzip 流前兩個字節是0x1e8b ,不是0x1f8b .後來檢查一下code ,代碼處理錯誤,加上第二個字節的時候需 &0xFF

0x1f8b 可參考標准 http://www.gzip.org/zlib/rfc-gzip.html#file-format

Copyright © Linux教程網 All Rights Reserved