轉自:https://www.jianshu.com/p/fa6664cda808
使用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