Apache HTTP client or URLConnection [duplicate]
I need to download a web page on an Android app and I am having a hard time deciding whether to use the Android Apache HTTP client or Java's URLConnection.
Any thoughts?
Google has silently deprecated Apache HTTP client usage since Gingerbread: http://android-developers.blogspot.com/2011/09/androids-http-clients.html. And while they didn't mark it with deprecated annotation, they suggest you to use HttpURLConnection for new applications as: it is where we [Google] will be spending our energy going forward
.
Personally I don't like that decision and would rather stick to HttpClient 4.1+, as it is faster, have fewer bugs and is updated regularly. And while you can not upgrade system library to version 4.1, you can include HttpClient jar to your Android project (as the additional benefit this would allow you to not depend on Google bug fixes and vendor updates). There is one pitfall however: to prevent possible collisions with built-in library you should rename httpclient packages using JarJar tool. Turned out someone already did this (repackaged jar and Android library projects are available for download):
http://code.google.com/p/httpclientandroidlib/
This is a repackaging of HttpClient 4.1 for Android. The version of HttpClient in the Android SDK is 4.0beta2. There have been several updates to HttpClient and some much-needed bugfixes like auth caching since the 4.0beta.
Since Google has deprecated HttpClient in favor of Java standard HttpURLConnection I created a script to convert a stock release of Apache's HttpClient into an Android library.
Changes to stock HttpClient
- Renamed all packages org.apache.http to ch.boye.httpclientandroidlib
- Deleted all classes dependent on org.ietf.* (SPNEGO authentication)
- Replaced org.apache.commons.codec.binary.Base64 with android.util.Base64
- Created a new class HttpClientAndroidLog to replace org.apache.commons.logging
For most things I'd say that HttpClient
is the way to go. However there are some situations and edge cases where I'd fall back to a URLConnection
. Examples of edge cases here and here
EDIT
A similar question has been asked before: httpclient vs httpurlconnection. I would assume that I would find HttpUrlConnection
is somewhat faster as the HttpClient
is built on top of the standard Java libraries. HoweverHttpClient
code much quicker and easier to write and maintain. According to a comments below, the core elements of HttpClient
have been performance optimised.
If performance is a major concern your best bet is to write two clients, one using each method, then benchmark them both. If you do this, please let us know the results.
in Gingerbread and later, HttpURLConnection is the way to go. consider Apache HttpClient deprecated. (also note that Android doesn't use HttpClient 4.1, mentioned in another comment.)
if you have a case where Apache HttpClient is faster, report it as a bug here: http://code.google.com/p/android/issues/list
精彩评论