Android网络连接的两种方法:apache client和httpurlconnection的比较

另见http://blog.csdn.net/mingli198611/article/details/8766585

在官方blog中,android工程师谈到了如何去选择apache client和httpurlconnection的问题: 
  原文见http://android-developers.blogspot.com/2011/09/androids-http-clients.html 
这里小结下几点。 

1) apache httpclient比较稳定点,少BUG,但由于API的关系,扩展改造麻烦点, 
所以android team现在不鸟这东西了基本 

2) httpurlconnection比较轻便,灵活,易于扩展,在2。2前有个BUG, 
见http://code.google.com/p/android/issues/detail?id=2939 
  可以通过如下代码去解决: 
 
Java代码   收藏代码
  1. private void disableConnectionReuseIfNecessary() {    
  2.   // HTTP connection reuse which was buggy pre-froyo     
  3.  if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {        System.setProperty("http.keepAlive""false");     
  4.  }  
  5. }  

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

4) 对HTTPURLCONECTION中,在3。0后以及4。0中都进行了改善,比如对HTTPS的支持, 
在4。0中,还增加了对缓存的支持呢!比如下面的代码: 
Java代码   收藏代码
  1. private void enableHttpResponseCache()   
  2. {    
  3.   try {  
  4.         long httpCacheSize = 10 * 1024 * 1024// 10 MiB      
  5.     File httpCacheDir = new File(getCacheDir(), "http");      
  6.     Class.forName("android.net.http.HttpResponseCache").getMethod("install", File.classlong.class.invoke(null, httpCacheDir, httpCacheSize);     
  7.  }   
  8. catch   
  9. (Exception httpResponseCacheNotAvailable) {    
  10.   }  
  11. }  


  最后的建议,Gingerbread后的版本,都建议用httpurlconnection,获得更高的性能



另有文章:

以下是官方原文(地址:http://developer.android.com/training/basics/network-ops/connecting.html

---------------原文-------------------------

Most network-connected Android apps use HTTP to send and receive data. Android includes two HTTP clients: HttpURLConnection and Apache HttpClient. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6, and connection pooling. We recommend using HttpURLConnection for applications targeted at Gingerbread and higher. For more discussion of this topic, see the blog post Android's HTTP Clients.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值