大多数网络相关的Android应用都会使用HTTP来接收和发送数据。Android中有2种HTTP客户端:HttpURLConnection 和Apache HTTP Client. 它们都支持HTTPS,文件流上传和下载,IPv6,并可以配置超时和连接池。
Apache HTTP Client
DefaultHttpClient和与它类似(sibling)的AndroidHttpClient 都是可拓展的支持web浏览器的HTTP客户端.它们都有着繁多而复杂的API,实现都很稳定,很少有Bug.
但是大量繁杂的API使得想不打破兼容性去改进它们变得非常困难.所以Android Team 不再维护(actively working)Apache HTTP Client.
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.
HttpURLConnection
HttpURLConnection是一个多用途的(general-purpose)、轻量级的HTTP客户端,适用于大多数的应用。这个类有点简陋(humble beginnings),但是它的 focused API使得我们可以稳定的进行改进.
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.
在Android Froyo之前,HttpURLConnection 有很多令人诅丧的bug.尤其是,在一个可读的InputStream上调用close()会摧毁连接池(poison the connection pool). 可以通过关闭连接池来解决:
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");
}
}
在Gingerbread中,我们添加了传输层的response压缩(comprression). HttpURLConnection会自动把这个头消息(header)添加到返回的request里,并处理对应的回复:
Accept-Encoding: gzip
应该充分利用这一点,可以通过配置你的web服务器来为客户端压缩response来支持它.
如果response压缩存在问题,这个类的文档 会告诉你如何关闭它.
自从HTTP的内容长度头返回了压缩的大小,使用 getContentLength() 来为未压缩的数据计算buffers的长度。相反的,从 response里读取bytes直到InputStream.read()返回-1.在GingerBread中我们在HTTPS上也作出了一些改进。 HttpsURLConnection在连接时会尝试使用Server Name Indication(SNI),这个允许多个HTTPS 主机共享一个IP地址,它也支持压缩和Session标签(Session tickets).当连接失败时,它会自动重试 without these features.这使得HttpsURLConnection在连接最新的(up-to-date)服务器时更有效,而不用破坏与旧服务器的兼容性.
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.We also made several improvements to HTTPS in Gingerbread. [HttpsURLConnection] attempts to connect with Server Name Indication 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.
在Ice Cream Sandwich中,我们添加了一个response缓存.使用这个缓存,HTTP 请求可以满足使用下面三种方式中的一种:
所有缓存的回复都会从 本地存储器中直接读取并提供出来。因为无网络连接需要这种回复立即可见。
有条件的缓存的回复应该有web服务器的freshness验证.客户端会发送一个request,比如 “Give me /foo.png if it changed since yesterday” .服务器会进行response,或回复一个最新的内容(内容发生更改),后返回一个304 Not Modified消息(内容未更改).
未缓存的response则是由服务器提供.这些回复会被存储起来已备后面使用.
Uncached responses are served from the web. These responses will get stored in the response cache for later.
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 a 304 Not Modified
status. If the content is unchanged it will not be downloaded!
使用反射来开启设备上的HTTP response缓存来支持这个特性.下面的示例会打开 Ice Cream Sandwich版本上的response缓存而不会影响更早的版本.
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)
{ }}
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:
你也可以通过配置你的web服务器来在你的HTTP回复中设置缓存头。
You should also configure your Web server to set cache headers on its HTTP responses.
哪一个客户端是最佳的呢?
Apache HTTP client在Eclair 和 Froyo中有着更少的bug.在这些发行版中这是最好的选择.
对于Gingerbread 和之后的版本, HttpURLConnection 是最佳的选择.它简洁的API和小的体积使它更能适合Android.传输压缩和response缓存减少了网络使用,提高了速度并且更加省电。新的应用应该使用 HttpURLConnection,这也是我们以后发力的方向。
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.