close

Google 為了使用者資料和裝置的安全性

升到 Android 9 的時候在 network 方面做了一項改變

Android 預設將使用加密連線

這意味著所有連線、不論傳送或接收,都不能明碼傳輸

所以在我們使用 http 協定的時候就會報錯

錯誤如下

 

HttpUrlConnection 版:

W/System.err: java.io.IOException: Cleartext HTTP traffic to **** not permitted

 

OKHttp 版:

java.net.UnknownServiceException: CLEARTEXT communication ** not permitted by network security policy

 

解法有 3

1、改使用 Https 協定

2、targetSdkVersion 降至 27 以下 ( 但 2019/08/01 Google 已強制開發者升到 28 )

3、修改預設,配置網路安全設定

 

前兩項大家應該都知道了

那麼第三項要怎麼做呢?

官方也有文件可讀

首先在 rsc/xml 目錄下建立 network_security_config.xml

內容為

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

再來到 Mainfast.xml 的 application 加入以下屬性

<application
    android:networkSecurityConfig="@xml/network_security_config"
    。。。

 

這樣子 Android P 的系統就可以改掉預設,使用 http 協定了

 

 

 

參考資料:

https://developer.android.com/training/articles/security-config

 

 

 

 

 

 

 

 

 

 

 


arrow
arrow

    顏澤偉 發表在 痞客邦 留言(1) 人氣()