Search code examples
javaandroidhttpapache-httpcomponents

How can I use the latest HttpComponents version on Android?


I was using the HttpComponents library that Android comes with. I wrote 2 classes to send params with GET and POST and to recieve an InputStream or a String from the server. All was working fine: every download on a thread, start, pause, resume... But today I've started two downloads simultaneously and none of them have finished.

I've googled a solution and I've seen that Android comes with HttpCore 4.0-beta2. Yes, it's very old. It was released on 01 July 2008 and Android hasn't updated it since then...

I've rewritten my classes but now using HttpURLConnection and I can download two files at the same time.

OK, that was a warning for you if you are considering using HttpComponents on Android. Now my question. I want to import the new version 4.1 to my project. I've added the jars to the built path, but now how can I use these jars if the new (4.1) and the old (beta2, 4.0) packages are the same?

Thanks.

SOLVED
You have to create the DefaultHttpCLinet with a ThreadSafeClientConnManager:

HttpParams parameters = new BasicHttpParams ();
HttpProtocolParams.setVersion (parameters, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset (parameters, HTTP.UTF_8);
HttpProtocolParams.setUseExpectContinue (parameters, false);
ConnManagerParams.setMaxTotalConnections (parameters, MAX_CONNECTIONS);

SchemeRegistry schReg = new SchemeRegistry ();
schReg.register (new Scheme ("http", PlainSocketFactory.getSocketFactory (), 80));

client = new DefaultHttpClient (new ThreadSafeClientConnManager (parameters, schReg), parameters);

UPDATE: You can also use AndroidHttpClient. With this class you don't need to use ThreadSafeClientConnManager

AndroidHttpClient client = AndroidHttpClient.newInstance ("Android");

More info


Solution

  • But today I've started two downloads simultaneously none of them finished.

    Because HttpClient is not thread-safe by default. You have to hook up a ThreadSafeClientConnManager for that. This is covered in the HttpClient documentation.

    I've googled a solution and I've seen that Android comes with HttpCore 4.0-beta2. Yes, it's very old. It was released on 01 July 2008 and Android hasn't updated it since then... and it's BUGGED

    https://android.googlesource.com/platform/external/apache-http

    Please notice that there are quite a few commits since "01 July 2008".

    I've rewritten my classes but now using HttpURLConnection and I can download two files at the same time.

    Most programmers can do this with HttpClient as well.

    how can I use these jars if the new (4.1) and the old (beta2, 4.0) packages are the same?

    You can't.