官方意见:
1) apache httpclient比较稳定点,少BUG,但由于API的关系,扩展改造麻烦点,
所以android team现在不鸟这东西了基本
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");
}
}
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)在androidSDk中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版本的架构做全面地分析。