Android’s HTTP Clients--Android HTTP 客户端选择

大多数网络相关的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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,087评论 18 139
  • 原文https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html...
    梁行之阅读 983评论 0 0
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,544评论 25 707
  • 我能想到最好的时光,便是老光阴, 我能记住最美的刹那,也是那些泛着旧色的陈年记忆! 独自逛小街,转转旧书摊,拿起一...
    时光散落在人间阅读 296评论 4 5
  • 1、Butterknife是什么? Butterknife是一个依托Java的注解机制来实现辅助代码生成的框架 2...
    DevWang阅读 1,611评论 0 52