qweewq123qwe 发表于 2015-8-5 11:15:05

android 中对apache httpclient及httpurlconnection的选择

在官方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代码
[*]private void disableConnectionReuseIfNecessary() {   
[*]// HTTP connection reuse which was buggy pre-froyo   
[*] if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {      System.setProperty(&quot;http.keepAlive&quot;, &quot;false&quot;);   
[*] }
[*]}

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

4) 对HTTPURLCONECTION中,在3。0后以及4。0中都进行了改善,比如对HTTPS的支持,
在4。0中,还增加了对缓存的支持呢!比如下面的代码:



Java代码
[*]private void enableHttpResponseCache()   
[*]{   
[*]try {
[*]      long httpCacheSize = 10 * 1024 * 1024; // 10 MiB      
[*]    File httpCacheDir = new File(getCacheDir(), &quot;http&quot;);      
[*]    Class.forName(&quot;android.net.http.HttpResponseCache&quot;).getMethod(&quot;install&quot;, File.class, long.class.invoke(null, httpCacheDir, httpCacheSize);   
[*] }   
[*]catch   
[*](Exception httpResponseCacheNotAvailable) {   
[*]}
[*]}


最后的建议,Gingerbread后的版本,都建议用httpurlconnection,获得更高的性能
页: [1]
查看完整版本: android 中对apache httpclient及httpurlconnection的选择