1. 程式人生 > >Http gzip的壓縮原理

Http gzip的壓縮原理

進入主題之前,我們先來看一下客戶端與伺服器通訊過程中,如果伺服器支援,HTTP gzip壓縮是如何實現的?

如圖所示:

這裡寫圖片描述
request header中宣告Accept-Encoding: gzip,告知伺服器客戶端接受gzip的資料。
伺服器支援的情況下,返回gzip後的response body,同時加入以下header:

Content-Encoding: gzip:表明body是gzip過的資料
Content-Length:117:表示body gzip壓縮後的資料大小,便於客戶端使用。

Transfer-Encoding: chunked:分塊傳輸編碼
OK,HTTP gzip壓縮的基本流程我們理清楚了,來看在Android各網路框架中表現有什麼差異。

OkHttp

OkHttp作為目前Android最火的網路庫,應用範圍較廣,相比於Android自帶的HttpUrlConnection、Apache坑也少很多。
我們首先來看這個庫的實現:
(注:以下程式碼基於OkHttp 3.4.1, 之前的版本邏輯也是一樣的,但3.4.0開始將這些邏輯抽離到了內建的interceptor中,看起來較為方便)

BridgeInterceptor.java

// If we add an “Accept-Encoding: gzip” header field we’re responsible for also decompressing
// the transfer stream.
boolean transparentGzip = false;
if (userRequest.header(“Accept-Encoding”) == null) {
transparentGzip = true;
requestBuilder.header(“Accept-Encoding”, “gzip”);
}
如果header中沒有Accept-Encoding,預設自動新增 ,且標記變數transparentGzip為true。

if (transparentGzip
&& “gzip”.equalsIgnoreCase(networkResponse.header(“Content-Encoding”))
&& HttpHeaders.hasBody(networkResponse)) {
GzipSource responseBody = new GzipSource(networkResponse.body().source());
Headers strippedHeaders = networkResponse.headers().newBuilder()
.removeAll(“Content-Encoding”)
.removeAll(“Content-Length”)
.build();
responseBuilder.headers(strippedHeaders);
responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
}
針對返回結果,如果同時滿足以下三個條件:

transparentGzip為true,即之前自動添加了Accept-Encoding
header中標明瞭Content-Encoding為gzip
有body
移除 Content-Encoding、Content-Length,並對結果進行解壓縮。

可以看到以上邏輯完成了:

開發者沒有新增Accept-Encoding時,自動新增Accept-Encoding: gzip
自動新增的request,response支援自動解壓
手動新增不負責解壓縮
自動解壓時移除Content-Length,所以上層Java程式碼想要contentLength時為-1
自動解壓時移除 Content-Encoding
自動解壓時,如果是分塊傳輸編碼,Transfer-Encoding: chunked不受影響。
以上6點是我們通過OkHttp原始碼得出的結論,我們以此來繼續看下其他框架。

HttpUrlConnection

  1. 是否自動新增Accept-Encoding: gzip

官網有過說明:

In Gingerbread, we added transparent response compression. HttpURLConnection will automatically add this header to outgoing requests, and handle the corresponding response:
Accept-Encoding: gzip
Take advantage of this by configuring your Web server to compress responses for clients that can support it. If response compression is problematic, the class documentation shows how to disable it.
即:2.3後預設是gzip,不加Accept-Encoding會被自動新增上Accept-Encoding: gzip。

  1. 自動新增的request,response是否支援自動解壓

By default, this implementation of HttpURLConnection requests that servers use gzip compression and it automatically decompresses the data for callers of getInputStream().
即返回的資料是已經自動解壓縮的。

  1. 手動新增是否負責解壓縮

By default, this implementation of HttpURLConnection requests that servers use gzip compression and it automatically decompresses the data for callers of getInputStream(). The Content-Encoding and Content-Length response headers are cleared in this case. Gzip compression can be disabled by setting the acceptable encodings in the request header:
urlConnection.setRequestProperty(“Accept-Encoding”, “identity”);
Setting the Accept-Encoding request header explicitly disables automatic decompression and leaves the response headers intact; callers must handle decompression as needed, according to the Content-Encoding header of the response.
例子中只提到設定為identity時可以禁止gzip壓縮。
但是請注意最後一段提到,顯式宣告會禁止自動解壓,同時保留header完整性,需要根據Content-Encoding來自己處理response。

實測4.1 - 6.0 版本之後發現,並不是非要指定identity才能遮蔽,指定gzip一樣也不會解壓縮。so,只要是顯式宣告過,都不會再處理,即:手動新增不會負責解壓縮。

  1. 自動解壓時Content-Length問題

Since HTTP’s Content-Length header returns the compressed size, it is an error to use getContentLength() to size buffers for the uncompressed data. Instead, read bytes from the response until InputStream.read() returns -1.
即:getContentLength() 值為gzip壓縮時的資料大小。

之前提到OkHttp在處理gzip壓縮時會把Content-Length移除,contentLength在Java層獲取為-1,而HttpURLConnection 在Android 4.4以後底層是由OkHttp實現的,那文件中提到的getContentLength()是compressed size是否還繼續成立呢?

實測後發現 :

4.4之後的版本,Content-Length被移除,getContentLength() = -1
2.3- 4.3之間,Content-Length 沒有移除,getContentLength() = compressed size
5. 自動解壓時的Content-Encoding

與Content-Length對應:

4.4之後的版本,Content-Encoding被移除
2.3- 4.3之間,Content-Encoding存在,無變化。
6. 自動解壓時的分塊編碼傳輸

與OkHttp相同,Transfer-Encoding: chunked不受影響。

Apache

這裡不再贅述,僅闡述結論:
無自動新增、解壓機制。

總結

1、是否支援自動新增Accept-Encoding與資料自動解壓?

name transparent response compression
OkHttp yes
HttpUrlConnection yes
Apache no
2、支援自動後,response header的表現如何?

name Content-Encoding: gzip Header : Content-Length Java : ContentLength
OkHttp 被移除 被移除 -1
HttpUrlConnection(2.3 ~ 4.3) 不變 不變 compressed size
HttpUrlConnection(4.4 ~ ?) 被移除 被移除 -1

name Content-Encoding: gzip Transfer-Encoding: chunked
OkHttp 被移除 不變
HttpUrlConnection(2.3 ~ 4.3) 不變 不變
HttpUrlConnection(4.4 ~ ?) 被移除 不變
3、自動模式啟動後,在Java中獲取contentLength無論是哪個版本的HttpUrlConnection還是OkHttp都是不可信的,都不是解壓縮之後的值(可能為-1或compressed size),因此最好不要通過contentLength來做什麼操作。

4、HttpUrlConnection、OkHttp均是手動新增不自動解壓縮,Apache沒有自動新增自動解壓功能。三者在手動新增Accept-Encoding後,表現一致(利用這個特點,可以做一個在三者之上的網路框架,隨意切換三種通道)。

參考資料

Android’s HTTP Clients
HttpURLConnection
HTTP 協議中的 Transfer-Encoding