java.io.IOException: Cleartext HTTP traffic to xxx.xxx.xxx.xxx not permitted
Android9.0 默認是禁止所有的http
請求的,需要在代碼中設置如下代碼才可以正常進行網絡請求: android:usesCleartextTraffic="true"。如圖
-
<application
-
android:name= "xxxx.xxxx.xxx.xxx"
-
android:allowBackup= "true"
-
android:icon= "@drawable/ic_launcher"
-
android:label= "@string/app_name"
-
android:theme= "@style/AppBaseTheme"
-
android:usesCleartextTraffic= "true">
-
Android高版本聯網失敗報錯:Cleartext HTTP traffic to xxx not permitted解決方法
前言:為保證用戶數據和設備的安全,Google針對下一代 Android 系統(Android P) 的應用程序,將要求默認使用加密連接,這意味着 Android P 將禁止 App 使用所有未加密的連接,因此運行 Android P 系統的安卓設備無論是接收或者發送流量,未來都不能明碼傳輸,需要使用下一代(Transport Layer Security)傳輸層安全協議,而 Android Nougat 和 Oreo 則不受影響。
因此在Android P 使用HttpUrlConnection進行http請求會出現以下異常
W/System.err: java.io.IOException: Cleartext HTTP traffic to **** not permitted
使用OKHttp請求則出現
java.net.UnknownServiceException: CLEARTEXT communication ** not permitted by network security policy
在Android P系統的設備上,如果應用使用的是非加密的明文流量的http網絡請求,則會導致該應用無法進行網絡請求,https則不會受影響,同樣地,如果應用嵌套了webview,webview也只能使用https請求。
針對這個問題,有以下三種解決方法:
(1)APP改用https請求
(2)targetSdkVersion 降到27以下
(3)更改網絡安全配置
前面兩個方法容易理解和實現,具體說說第三種方法,更改網絡安全配置。
1.在res文件夾下創建一個xml文件夾,然后創建一個network_security_config.xml文件,文件內容如下:
-
-
<network-security-config>
-
<base-config cleartextTrafficPermitted="true" />
-
</network-security-config>
2.接着,在AndroidManifest.xml文件下的application標簽增加以下屬性:
-
<application
-
...
-
android:networkSecurityConfig="@xml/network_security_config"
-
...
-
/>
完成,這個時候App就可以訪問網絡了。
