問題描述
在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
則不會受影響。
解決方案
分析:爲保證用戶數據和設備的安全,Google針對下一代 Android 系統(Android P) 的應用程序,將 要求默認使用加密連接,這意味着 Android P
將禁止 App
使用所有未加密的連接,因此運行 Android P 系統的安卓設備無論是接收或者發送流量,未來都不能明碼傳輸,需要使用下一代(Transport Layer Security)傳輸層安全協議。
針對這個問題,有以下四種解決方法,要使用哪一種方法那就看個人了,我覺得第四種比較簡單方便(極力推薦第四種):
(1)APP改用https
請求
(2)targetSdkVersion
降到27以下
(3)更改網絡安全配置
(4)在AndroidManifest.xml
配置文件的標籤中直接插入
android:usesCleartextTraffic="true"
注:
第三種方法具體如何實現呢?
1.在
res
文件夾下創建一個xml
文件夾,然後創建一個network_security_config.xml
文件,文件內容如下:<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config>
2.接着,在
AndroidManifest.xml
文件下的application
標籤增加以下屬性:<application ... android:networkSecurityConfig="@xml/network_security_config" ... />
完成,這個時候
App
就可以訪問網絡了。
個人網站:分享客(https://sharerdiary.com/)
這個網站經常分享一些免費視頻、免費音樂、實用工具和各種福利,感興趣的朋友可以看看!