一、前言
为保证用户数据和设备的安全,Google 针对下一代 Android 系统(Android P) 的应用程序,将要求默认使用加密连接,这意味着 Android P 将禁止 App 使用所有未加密的连接。因此运行 Android P 系统的安卓设备无论是接收或者发送流量,未来都不能明码传输,需要使用下一代(Transport Layer Security)传输层安全协议,而 Android Nougat 和 Oreo 则不受影响。
二、问题
在Android P 系统的设备上,如果应用使用的是 非加密的明文流量 的 http 网络请求,则会导致该应用无法进行网络请求,https 则不会受影响。同样地,如果应用嵌套了 webview,webview 也只能使用 https 请求。
在 Android P 使用 HttpUrlConnection 进行 http 请求会出现以下异常:
W/System.err: java.io.IOException: Cleartext HTTP traffic to **** not permitted
使用 OKHttp 请求则出现:
java.net.UnknownServiceException: CLEARTEXT communication to **** not permitted by network security policy
三、解决方案
针对这种情况,有以下四种解决方案:
-
APP 改用 https 请求。条件允许的话,建议使用,以增强安全性。
-
Android 编译的 targetSdkVersion 改为27以下。因为是高版本才出现的,那可以降维处理。
-
在 AnroidManifest.xml 中的 application 添加设置项:
<application android:usesCleartextTraffic=“true”> -
添加网络安全配置。
在 res 的 xml 目录下,新建一个 network_config.xml 文件(名称随便取):
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
然后在 AnroidManifest.xml 中的 application 添加指向该文件的设置项:
<application
...
android:networkSecurityConfig="@xml/network_config"
...
/>
5.
非Activity-Context启动Activity,现在强制执行 FLAG_ACTIVITY_NEW_TASK 要求,Apache HTTP 客户端弃用,影响采用非标准 ClassLoader 的应用。
在项目中用到了 Apache HTTP client 的相关类,就会抛出找不到这些类的错误。这是因为官方已经在 Android P 的启动类加载器中将其移除,如果仍然需要使用 Apache HTTP client.
Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.protocol.BasicHttpContext" on path: DexPathList”
在 AnroidManifest.xml 中的 application 添加:
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />