avatar

OKHTTP发送请求无回应

OKHTTP发送请求无回应

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

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

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

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

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

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

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

1
2
3
4
5
6
7
<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>
文章作者: pengweifu
文章链接: https://www.pengwf.com/2019/10/23/android/ANDROID-Okhttp/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 麦子的博客
打赏
  • 微信
    微信
  • 支付宝
    支付宝

评论