天天看點

android中httpclient和HttpURLConnection優缺點和常見bug解決方法

http://blog.csdn.net/androidzhaoxiaogang/article/details/8158122

官方意見:

1) apache httpclient比較穩定點,少bug,但由于api的關系,擴充改造麻煩點,

是以android team現在不鳥這東西了基本

2) httpurlconnection比較輕便,靈活,易于擴充,在2。2前有個bug,

見http://code.google.com/p/android/issues/detail?id=2939

  可以通過如下代碼去解決:

[java] view

plaincopy

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) {    

  }  

  谷歌的的建議是,gingerbread後的版本,都建議用httpurlconnection,獲得更高的性能

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版本的架構做全面地分析。

繼續閱讀