使用OkHttp3在Android P 出现的错误:CLEARTEXT communication to host not permitted by network

问题描述:

使用OkHttp3做网络请求框架时,如果是http请求而非https请求,会导致请求失败,因为Android P之后系统限制了明文的网络请求,非加密请求会被系统禁止掉。

同样如果您使用了WebView加载http协议下的页面,也会出现加载失败,https则不受影响。

分析:

OkHttp3的源码可以看到,它做了请求的检查

if (!Platform.get().isCleartextTrafficPermitted(host)) {
      throw new RouteException(new UnknownServiceException(
          "CLEARTEXT communication to " + host + " not permitted by network security policy"));
}

如果请求是明文流量,默认情况下,在Android P版本Okhttp3就会抛出异常:

CLEARTEXT communication to " + host + " not permitted by network security policy

解决办法:

1.禁用掉明文流量请求的检查

在 res 下新建一个 xml 目录,然后创建一个名为:network_security_config.xml 文件 ,该文件内容如下:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

然后在 AndroidManifest.xml application 标签内应用上面的xml配置:

<application
        android:name=".App"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:theme="@style/AppTheme"></application>

2.推荐方式

服务器和本地应用都改用 https

3.修改应用目标版本

将targetSdkVersion 降级回到 27

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容