7

After Android 6.0 releases, Support for the Apache HTTP client is removed. If our app is using this client and targets Android 2.3 (API level 9) or higher, HttpURLConnection class is recommended. It's said that this API is more efficient because it reduces network use through transparent compression and response caching, and minimizes power consumption. If we want to continue using the Apache HTTP APIs, you must first declare the following compile-time dependency in our build.gradle file:

android {
    useLibrary 'org.apache.http.legacy'
}

The legacy jar is in Android SDK, whose path is sdk/platforms/android-23/optional/. So, it is nearly independent. Meanwhile, this apache legacy jar is putted into optional/ in Android SDK, so what is optional/? What does that mean?

Also we know, we can put this jar into libs and then declare it in our build.gradle file like this:

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

Both methods worked as expected when I tested.

But why?

What's the difference between useLibrary and compile files('') in build.gradle? Only because the legacy jar file is in android SDK so I can declare useLibrary in build.gradleto use it? Could I use other jars in this way?

Could somebody provide some ideas about this?

Lii
  • 11,553
  • 8
  • 64
  • 88
SilentKnight
  • 13,761
  • 19
  • 49
  • 78

1 Answers1

12

useLibrary adds the library to classpath while compiling but does not bundle the library with the application.

compile dependencies are in classpath at compile time and additionally they get shipped with your APK.

For the Apache HttpClient support, use useLibrary when compiling with SDK 23+. The library is already there in the target platform. It is just not there in the compile SDK.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • What do you mean by `The library is already there in the target platform`? If my `targetSDK` is 23+, is it so? – SilentKnight Oct 08 '15 at 11:38
  • It's there in the libraries preinstalled on your device. TargetSDK controls what backwards compatibility modes are enabled, not what libraries are installed. – laalto Oct 08 '15 at 11:39
  • So, libraries pre-installed in devices and Android SDK we develop on are not the same thing? Could you describe in more details? – SilentKnight Oct 08 '15 at 11:42
  • 2
    If you have a look at the SDK android.jar you compile with, it's all just stubs throwing exceptions. It's not the same in a runtime environment. – laalto Oct 08 '15 at 11:51