在官方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("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中,還增加了對緩衝的支援呢!比如下面的代碼:
Java代碼
- 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)