Use Apache HTTP Client on Android SDK 23

With the Android M SDK (API 23), Google removed the Apache HTTP Client library.
It was deprecated since API 22, and Google recommanded to use
HttpURLConnection instead since API 9. While the classes are still bundled in
Android 6 ROMs, it won’t be long until we see them completely go away.

Some applications are still relying on this library, and need to be updated to
use the SDK 23, without having time/budget/whatever required to switch from
HTTP Client. While I strongly recommend you to still take time to move to
something else (there are many high-level libraries, like
OkHttp or
Ion, or you can use HttpURLConnection
to keep a low-level access), there is a way to use the Apache library
while using the SDK 23.

Current situation

The Android SDK is mainly a JAR of empty stubs, which allows the build system to
assemble an APK depending on theses stubs. But the JAR is not bundled in the
APK. At runtime, Android will provide actual implementations of all these
classes and their methods. That’s a rough explanation, but we don’t have to go
more in-depth to explain the issue we have with the SDK 23.

In this new SDK, Google simply removed the stubs for the Apache HTTP Client
library. As a result, any application using it doesn’t build anymore. But… an
old APK still works on devices running on Android M. The explanation is simple:
the stubs have been removed, but not the matching classes on the device. The
solution seems obvious: we need to get back those stubs!

Fixing the problem on a Gradle project

Using the build-tools 23 and the SDK 23 (well, you won’t have the issue without
it anyway), providing stubs for the Apache library is really easy. Simply
add this command in the android section of your build.gradle:

build.gradle
1
2
3
android {
        useLibrary 'org.apache.http.legacy'
}

Rebuild, problem solved.

Other project types

If you’re not using Gradle, the solution is not much more complicated. Google is
providing a JAR with the stubs you need. That’s the one used by Gradle. You can
find it in your SDK: platforms/android-23/optional/org.apache.http.legacy.jar.
Simply build against this JAR, and you’ll be fine.

In both cases, please remember to actually fix this by not using the Apache HTTP
Client library anymore as soon as possible, as it will probably be deleted in a
future Android release.

Source: Marc Plano-Lesay