解決Android9.0上無法使用Http協議

問題定義

           Android 9不讓客戶端通過非https方式訪問服務端數據(不允許發送明文http請求),Google表示,爲保證用戶數據和設備的安全,針對下一代 Android 系統(Android P) 的應用程序,將要求默認使用加密連接,這意味着 Android P 將禁止 App 使用所有未加密的連接,因此運行 Android P 系統的安卓設備無論是接收或者發送流量,未來都不能明碼傳輸,需要使用下一代(Transport Layer Security)傳輸層安全協議,而 Android Nougat 和 Oreo 則不受影響。

因此在Android9.0上 使用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.在項目文件夾建一個子文件夾res/xml,添加network_security_config.xml文件,並保存到res/xml下。

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

2.在AndroidManifest.xml引用

<application
    android:networkSecurityConfig="@xml/network_security_config"
    ...">
    ...    
</application>

 

參考:https://www.cnblogs.com/renhui/p/9921790.html

 

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