How to use the legacy Apache HTTP client on Android Marshmallow?

android developer picture android developer · Jul 27, 2015 · Viewed 90.2k times · Source

Background

On Android Marshmallow, Google has completely removed the support of Apache HTTP client (link here) because it doesn't have good performance compared to the alternatives.

This might also be the cause for so many apps crashing on Android Marshmallow.

The problem

Google allows you to still use this API, just not as a built in one, by adding this line to the gradle file:

useLibrary 'org.apache.http.legacy'

So, this is what I did:

dependencies {
    classpath 'com.android.tools.build:gradle:1.3.0'
}

And:

android {
    compileSdkVersion 'android-MNC'
    buildToolsVersion "23.0.0 rc3"
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.example.user.androidmtest"
        minSdkVersion 'MNC'
        targetSdkVersion 'MNC'
        versionCode 1
        versionName "1.0"
    }

When I tried it, it compiled fine (no errors being shown, and I could run the proof-of-concept app, as it doesn't have any special code), but when I tried using some of the classes that I know that are part of the old API (like "HttpClient" class), I see that it doesn't allow me to do so.

I know it's not recommended to use this solution, but we must have the app ready to work there at least temporarily, till we work 100% on all of the things that should change for Android Marshmallow, and we don't want surprises in the form of crashes.

Here's a screenshot:

enter image description here

The question

Why does it occur? Did I use it correctly?


EDIT: reported about this issue here:

https://code.google.com/p/android/issues/detail?id=181474

Answer

CoPLaS picture CoPLaS · Aug 18, 2015

Android Studio was complaining that org.apache.http classes like

org.apache.http.NameValuePair
org.apache.http.client.utils.URLEncodedUtils

were missing.

So I added org.apache.http.legacy.jar which is in Android/Sdk/platforms/android-23/optional folder to to app/libs

I also added this line to my app.gradle file

compile files('libs/org.apache.http.legacy.jar')

But if you're using more libraries, you can use this way

compile fileTree(dir: 'libs', include: ['*.jar'])

This resolved all my errors that were caused because google removed support of Apache HTTP client.