原因
參考:https://blog.csdn.net/qq_18620851/article/details/80617549
Android P 限制了明文流量的網(wǎng)絡(luò)請求,非加密的流量請求都會被系統(tǒng)禁止掉袍冷。
如果當前應用的請求是 htttp 請求,而非 https ,這樣就會導系統(tǒng)禁止當前應用進行該請求胡诗,如果 WebView 的 url 用 http 協(xié)議邓线,同樣會出現(xiàn)加載失敗煌恢,https 不受影響骇陈。
為此瑰抵,OkHttp3 做了檢查,所以如果使用了明文流量二汛,默認情況下婿崭,在 Android P 版本 OkHttp3 就拋出異常: CLEARTEXT communication to " + host + " not permitted by network security policy
if (!Platform.get().isCleartextTrafficPermitted(host)) {
throw new RouteException(new UnknownServiceException(
"CLEARTEXT communication to " + host + " not permitted by network security policy"));
}
解決方案
1:在 res 下新建一個 xml 目錄肴颊,然后創(chuàng)建一個名為:network_security_config.xml 文件 ,該文件內(nèi)容如下:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
文件位置
2.然后在 AndroidManifest.xml application 標簽內(nèi)應用上面的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>
示例圖片
擴展
networkSecurityConfig介紹https://developer.android.com/training/articles/security-config?hl=zh-cn