4

Apache has deprecated DefaultHttpClient, but it seems this is not the case for Android, see also here Deprecated Java HttpClient - How hard can it be?

Importing

org.apache.httpcomponents:httpclient:4.3.5

instead of

new DefaultHttpClient(); 

I would now use

HttpClient httpClient = HttpClientBuilder.create().build();

to create an http client. This works fine in a Java project, but when used in an Android project, the following import is missing

import org.apache.http.impl.client.HttpClientBuilder;

while

HttpClient sendClient =  new DefaultHttpClient();

is not marked as deprecated in Android and compiles fine.

I don't want to add the Apache httpclient a second time (and if I would do so, Android Studio would exclude it anyhow).

The Android documentation says here http://developer.android.com/reference/android/net/http/AndroidHttpClient.html#newInstance(java.lang.String) to use

AndroidHttpClient.new Instance(string)

to "get an http client with reasonable defaults".

Does anybody know what is the correct way of creating an HttpClient on Android, and what would be the userAgent string!?

Community
  • 1
  • 1
Oliver Hausler
  • 4,900
  • 4
  • 35
  • 70
  • basically u wanna just hit post request or is there anything u wanna achive with HttpClient – KOTIOS Jan 02 '15 at 04:05
  • I am trying to create a long running http request to receive push notifications from a server. – Oliver Hausler Jan 02 '15 at 05:05
  • I don't really know Android's push notifications yet, but I feel you should let Android deal with them. Don't have a service running only to get push notifications, this will waste battery. I found a tutorial about Android's push notifications, hope that helps: https://parse.com/tutorials/android-push-notifications – Über Lem Jan 02 '15 at 19:59
  • Thanks @ÜberLem, but PushNotifications is a completely different technology and the drawback is that it won't work with iOS. Android is on the receiving side, so sockets should not be a problem in terms of battery life. If anybody has a contrary opinion, please post it here. – Oliver Hausler Jan 04 '15 at 01:20

2 Answers2

6

Google Android ships with an extremely outdated (pre-BETA) version of Apache HttpClient 4.0.

If you want to use newer Apache HttpClient APIs with Android you should consider using the official Android port.

ok2c
  • 26,450
  • 5
  • 63
  • 71
  • This answer is correct but it's better to use new port which doesn't add any suffixes: https://hc.apache.org/httpcomponents-client-4.5.x/android-port.html – Jehy Jun 03 '16 at 20:49
3

You need to add this line in your app Gradle

compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
Saleem
  • 31
  • 3