Android 9.0系統 CLEARTEXT communication to host not permitted by network

原文:https://blog.csdn.net/qq_18620851/article/details/80617549 

問題: 由於 Android P 限制了明文流量的網絡請求,非加密的流量請求都會被系統禁止掉。

如果當前應用的請求是 htttp 請求,而非 https ,這樣就會導系統禁止當前應用進行該請求,如果 WebView 的 url 用 http 協議,同樣會出現加載失敗,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 目錄,然後創建一個名爲: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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章