英文原文链接:http://android-developers.blogspot.sg/2011/09/androids-http-clients.html
今天面试被问到谷歌为何使用HttpURLConnection却弃用 Apache HttpClient,本人一脸茫然,瞬间变成小白,于是乎回家赶紧谷歌查看官方文档,一边翻译,一边学习一下,翻译不足之处,望大家指出。
原文标题:Android's HTTP Clients
[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 app 会使用 HTTP 来发送与接收数据。Android 提供了两种 HTTP clients:HttpURLConnection 与 Apache HttpClient。二者均支持 HTTPS、流媒体上传和下载、可配置的超时、IPv6 与连接池。
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 clients 。它们拥有强大而灵活的API。它们的实现是稳定的,与此同时他们也有一些bug。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的开发工作。
close()
on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:
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");
}
}
Accept-Encoding: gzip
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.
In Ice Cream Sandwich, we are adding a response cache. With the cache installed, HTTP requests will be satisfied in one of three ways:
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 a304 Not Modified
status. If the content is unchanged it will not be downloaded!
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) {
}
}