Importing a newer Apache HttpClient jar in Android

喜你入骨 提交于 2019-12-04 06:54:16
matiash

The problem is that Android already includes an older version (it's unclear exactly which, but around 4.0beta2) of Apache HttpClient.

When you add the jars of the new version as libraries of your application, duplicate classes are ignored when the APK is loaded. Since some new classes in HttpClient depend on modifications made on these other classes, dalvik does what it can (e.g. removing references, &c) but unless they are used conditionally, this is likely to cause crashes.

For example, you can see messages like these in logcat:

06-05 00:46:39.083: I/dalvikvm(6286): Could not find method org.apache.http.client.protocol.RequestDefaultHeaders.<init>, referenced from method org.apache.http.impl.client.HttpClientBuilder.build
06-05 00:46:39.083: W/dalvikvm(6286): VFY: unable to resolve direct method 22794: Lorg/apache/http/client/protocol/RequestDefaultHeaders;.<init> (Ljava/util/Collection;)V
06-05 00:46:40.434: D/dalvikvm(6286): DexOpt: couldn't find static field Lorg/apache/http/impl/client/DefaultHttpRequestRetryHandler;.INSTANCE
06-05 00:46:40.434: W/dalvikvm(6286): VFY: unable to resolve static field 8420 (INSTANCE) in Lorg/apache/http/impl/client/DefaultHttpRequestRetryHandler;

This particular message is because DefaultHttpRequestRetryHandler has a new INSTANCE static field in 4.3, which it does not have in Android. There are many more.

Going back to your original question, the only way to use a newer httpclient would be to rename all classes so these name conflicts don't occur. This is what httpclientandroidlib does.

Going even further back: DefaultHttpClient has indeed been deprecated in 4.3, but it is not deprecated in Android (unless you consider the trend towards using HttpUrlConnection a stealth form of deprecation -- in which case a newer HttpClient wouldn't be the preferred alternative either). Why exactly would you want/need to change it?

One year answer, correct answer is to use official android port of apache libraries which uses different namespace and so avoids collisions: https://hc.apache.org/httpcomponents-client-4.5.x/android-port.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!