天天看點

Google為何棄用HttpClient的而推薦使用HttpURLConnection

先說原因:

  1. 因為相容性問題,谷歌不願意維護HttpClient,而使用HttpURLConnection
  2. HttpURLConnection的API包小而簡便,更适合安卓
  3. HttpURLConnection能夠提高速度和提升電池性能

這是原文位址:

http://android-developers.blogspot.sg/2011/09/androids-http-clients.html

以下是原文和翻譯:

Android’s HTTP Clients

Jesse Wilson

[This post is by Jesse Wilson from the Dalvik team. —Tim Bray]

Most network-connected Android apps will use HTTP to send and receive data. Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.

大多數能聯網的Android應用會使用HTTP來發送和接收資料。Android提供了兩種HTTP用戶端:HttpURLConnection和Apache HTTP Client。二者均支援HTTPS、流式上傳和下載下傳、可配置的逾時、IPv6和連接配接池。

Apache HTTP Client

DefaultHttpClient and its sibling AndroidHttpClient are extensible HTTP clients suitable for web browsers. They have large and flexible APIs. Their implementation is stable and they have few bugs.

DefaultHttpClient和它的兄弟AndroidHttpClient都适合Web浏覽器擴充HTTP用戶端,它們擁有龐大而靈活的APIs,它們的實作很穩定并且很少有錯誤。

But the large size of this API makes it difficult for us to improve it without breaking compatibility. The Android team is not actively working on Apache HTTP Client.

但是,數目如此之多的API使得我們很難在不破壞相容性的情況下來進行優化。Android團隊也沒有積極處理Apache HTTP Client。

HttpURLConnection

HttpURLConnection is a general-purpose, lightweight HTTP client suitable for most applications. This class has humble beginnings, but its focused API has made it easy for us to improve steadily.

HttpURLConnection 是一個适合大多數應用的通用的,輕量級的HTTP用戶端。這個類出身卑微,但是它主要的API能夠使我們更容易的提升其穩定性。

Prior to Froyo, HttpURLConnection had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:

在Froyo之前的版本中,HttpURLConnection有許多令人崩潰的錯誤。尤其是在一個可讀的InputStream中調用close()會堵死連接配接池。通過禁用連接配接池解決此問題:

private void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
    System.setProperty("http.keepAlive", "false");
}
           

}

In Gingerbread, we added transparent response compression. HttpURLConnection will automatically add this header to outgoing requests, and handle the corresponding response:

在Gingerbread中,我們添加了透明響應壓縮。HttpURLConnection能夠自動的将這個頭部添加到傳出請求,并且能夠處理相應的響應:

Accept-Encoding: gzip

接受編碼: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.

可以利用通過配置web伺服器為可支援它的用戶端壓縮響應。如果響應壓縮有問題,在類文檔中示範了如何禁用它。

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.

由于HTTP的Content-Length的頭傳回壓縮後的大小,通過getContentLength()為未壓縮的資料擷取緩沖區大小是一個錯誤。替代的方法是,一直讀取位元組直到InputStream.read()傳回-1為止。

We also made several improvements to HTTPS in Gingerbread. HttpsURLConnection attempts to connect with Server Name Indication (SNI) which allows multiple HTTPS hosts to share an IP address. It also enables compression and session tickets. Should the connection fail, it is automatically retried without these features. This makes HttpsURLConnection efficient when connecting to up-to-date servers, without breaking compatibility with older ones.

我們還在Gingerbread中對HTTPS做了幾項改進。HttpsURLConnection試圖連接配接伺服器名稱訓示(SNI),它允許多個HTTPS站點在相同的IP位址上。它還支援壓縮和會話票證。如果連接配接失敗,則會在沒有這些功能的情況下自動重試。這使HttpsURLConnection能有效的連接配接到最新的伺服器,而不會破壞與舊的伺服器的相容性。

In Ice Cream Sandwich, we are adding a response cache. With the cache installed, HTTP requests will be satisfied in one of three ways:

在Ice Cream Sandwich中,我們增加了響應緩存。 安裝緩存後,HTTP請求将通過以下三種方式之一得到滿足:

  • Fully cached responses are served directly from local storage. Because no network connection needs to be made such responses are available immediately.
  • 完全緩存的響應直接從本地存儲提供。 因為不需要進行網絡連接配接,是以這樣的響應立即可用。
  • Conditionally cached responses must have their freshness validated by the webserver. The client sends a request like “Give me /foo.png if it changed since yesterday” and the server replies with either the updated content or a 304 Not Modified status. If the content is unchanged it will not be downloaded!
  • 有條件高速緩存的響應必須由Web伺服器驗證其新鮮度。 用戶端發送類似“給我/foo.png從昨天開始,如果它改變了”,而伺服器或者更新的内容或答複的請求304 Not Modified的狀态。 如果内容不變,則不會下載下傳!
  • Uncached responses are served from the web. These responses will get stored in the response cache for later.
  • 非緩存響應從網絡提供。 這些響應将存儲在響應緩存中以供稍後使用。

Use reflection to enable HTTP response caching on devices that support it. This sample code will turn on the response cache on Ice Cream Sandwich without affecting earlier releases:

使用反射在支援它的裝置上啟用HTTP響應緩存。此示例代碼将打開Ice Cream Sandwich上的響應緩存,而不會影響早期版本:

private void enableHttpResponseCache() {
    try {
        long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
        File httpCacheDir = new File(getCacheDir(), "http");
        Class.forName("android.net.http.HttpResponseCache")
            .getMethod("install", File.class, long.class)
            .invoke(null, httpCacheDir, httpCacheSize);
    } catch (Exception httpResponseCacheNotAvailable) {
    }
}
           

You should also configure your Web server to set cache headers on its HTTP responses.

您還應将Web伺服器配置為在其HTTP響應上設定緩存頭。

Which client is best?

哪個用戶端是最好的?

Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.

Apache HTTP用戶端在Eclair和Froyo上有更少的錯誤。 它是這些版本的最佳選擇。

For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where we will be spending our energy going forward.

對于Gingerbread和之後的版本,HttpURLConnection是最好的選擇。 它的簡單的API和小尺寸使它非常适合Android。 透明壓縮和響應緩存減少網絡使用,提高速度和節省電池。 新的應用程式應該使用HttpURLConnection; 這是我們将在未來花費我們的能量的地方。

水準有限,翻譯不足之處,望大家指出,多謝!