Android开发中联网时Http选择

这篇文章来自Android官方博客,其实很早就看过,因为需要翻墙并且原文为英文,所以现在翻译下来,记录一下,因为联网也是android开发最基本的一项,
也给了一些刚接触android开发的Http选择建议,因水平有限,关键部分附上了英文原文,语句不通顺也请谅解。
原文地址:http://android-developers.blogspot.jp/2011/09/androids-http-clients.html

几乎所有的Android应用联网都采用的Http协议,在Android平台上支持HttpUrlConnection和Apache HTTP Client。它们都支持Https,流的上传和下载,IPv6以及连接池。

Apache HTTP Client

DefaultHttpClient和 AndroidHttpClient对于浏览器来说是更合适的拓展客户端协议,它们有更强大更灵活的API,其实现也比较稳定,bug比较少。
但是大量的API也使我们在兼容方面更加困难,并且Android团队对HttpClinet的支持也不够积极。

HttpUrlConnection

HttpUrlConnection用途更广,对于应用来说更轻量级。其实现更底层,却方便我们利用API用完成我们的功能。
在2.1和2.2平台上,HttpUrlConnection有一个严重的bug。在一个可写流中调方法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”);
}
}

在2.3平台上HttpUrlConnection自动在Http header加了一个字段
Accept-Encoding: gzip
这样得到的HttpResponse会自动用Gzip压缩算法进行压缩。
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.
因此我们通过header Content-Length 获取的是压缩后的数据大小而不是我们期望的完整数据的大小,因此我们必须通过InputStream.read() 方法来获取response。
对Https同样有了几个方面改善,支持HttpUrlConnection通过SNI连接时用共享一个IP连接多个Https host。同时也支持了压缩和session。
当连接失败时,自动重连,这保证了HttpsURLConnection的更高效的和服务器同步。

Android4.0平台开始加入了response缓存,

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!

有一些缓存请求可能需要随时更新,这时我们向服务器发送一个请求确认服务器端是否有更新,当服务器端返回304的时候,证明服务器资源未更新,缓存可用。

Uncached responses are served from the web. These responses will get stored in the response cache for later.

response的缓存。
我们可以在代码中通过反射在Android4.0平台上支持缓存,并且不影响之前的版本,代码如下:

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

Http选择

Which client is best?
Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.
在2.1和2.2平台上,Apache HTTP client bug更少,是更合适的选择

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.
在2.3及以上,HttpURLConnection更合适,它更简单,更小。并且支持压缩和response缓存。

总结

其实就是我们直接用HttpUrlConnection就好了,因为现在几乎所有的Android手机rom版本最低基于android4.0,另外我们可以参考volley实现

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

在2.3以上,联网采用HttpUrlConnection的实现,
在2.3一下,采用HttpClient的实现。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值