android中httpclient和HttpURLConnection优缺点和常见bug解决方法

官方意见:

1) apache httpclient高效稳定,但是维护成本高昂,故android 开发团队不愿意在维护该库而是转投更为轻便的httpurlconnection;

2) httpurlconnection比较轻便,灵活和易于扩展,它在2.2前存在这样一个BUG,
详见http://code.google.com/p/android/issues/detail?id=2939
 

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");   
 }
}


3) 在Gingerbread中,httpurlconnection会增加对压缩报文头的处理,服务端可以用GZIP,详细见:
  http://developer.android.com/reference/java/net/HttpURLConnection.html

4) 在HTTPURLCONECTION中,在3.0后以及4.0中都进行了改善,如对HTTPS的支持,
在4.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) {  
  }
}

 

5)在android SDk中httpclient使用的是4.0beta2,我不得不说这个版本里面有些蛋疼的bug:

I.auth caching;

II.在4.0上的sdk,将wifi和3g同时打开,理论上来说,网络接口应该走wifi,但是却走了代理,导致访问服务器网络失败;

解决上面问题的唯一办法就是引入“http://code.google.com/p/httpclientandroidlib/”中的库,然后修改相应的类,典型的例子就是ThreadSafeClientConnManager变成了PoolingClientConnectionManager

个人意见:

我对谷歌官方开发同事的意见有点不敢雷同,个人更倾向于使用httpclient,因为从PoolingClientConnectionManager得解释我们就可以知道:

Manages a pool of {@link OperatedClientConnection client connections} and is able to service connection requests from multiple execution threads.
Connections are pooled on a per route basis. A request for a route which already the manager has persistent connections for available in the pool will be services by leasing a connection from the pool rather than creating a brand new connection.

可以节省我们频繁建立连接的时间,往往在我们的app里面更多的情况是,不断的去下拉列表调用接口,反复创建连接的代价可想而知。

请注意关注我后面的文章,我会对apache的httpclient 4.2版本的架构做全面地分析。


  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值