如何使用外部库在 Android 上使用的 Apache http-client 4.5.x

How to use Apache http-client 4.5.x used by external library on Android

我正在尝试了解 Android 当前与 Apache http 客户端的关系。我需要使用依赖于 org.apache.httpcomponents:httpclient:4.5.2 的标准 Java 库,但在 Android 上似乎是不可能的。

我们可以在 Android M 中看到,对于具有现代目标 sdk 的应用程序,support was removed for httpclient. And in Android P, the library was removed from the boot class path and is unavailable to apps without a manifest entry. I can also see that there is an official Apache which is a suitable direct replacement for 4.3.5.1 if you need a slightly more modern version of the library. And that there is even a third party port of 4.4.1.1

我的应用程序的最小 sdk 是 17,目标 sdk 是 28。所以我的第一个问题是,是否真的有可能杀死任何对 Android 版本的 apache httpclient 的引用,最小 sdk 卡在17,如果不是,我如何用库中的 4.5.2 替换该版本。

我的具体错误是 java.lang.NoSuchFieldError: org.apache.http.conn.ssl.AllowAllHostnameVerifier.INSTANCE,即使我的目标 SDK 为 28,Android 仍在寻找并使用遗留的 AllowAllHostnameVerifier.java class 而没有INSTANCE 字段:

您不能直接替换 Android 框架中包含的 类。唯一的解决方案是使用不同的命名空间。这就是为什么 Spongy Castle 使用 org.spongycastle.* 而不是 org.bouncycastle.*,并且您链接的项目使用 cz.msebera.android.httpclient.* 而不是 org.apache.http.*

不幸的是,这意味着您必须更改库中对 http-client 的所有引用。

自从 Android Jetpack 发布以来,SDK 包括 Jetifier,一个翻译工具 构建时库字节码中的引用。有一个standalone version,它可以使用自定义映射配置。

在你的情况下,这意味着:

  • 创建自定义配置,将 org.apache.http 转换为 cz.msebera.android.httpclient
  • 转换您的标准Java库
  • 使用改造后的库和http-client的第三方端口

另一种可能的转换库的解决方案是使用 Jar Jar.