1. 程式人生 > >Android 9.0/P http 網路請求的問題

Android 9.0/P http 網路請求的問題

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請求。

有人認為 Android P 上所有的 App 都需要使用 TLS 加密會降低上網體驗,事實上這是一種誤解,至於 App 對於少數舊伺服器的連線如果非要使用明碼傳輸,開發者需要更改 App 的網路安全配置以允許此類連線。

有以下三種解決方案

  • APP改用https請求
  • targetSdkVersion 降到27以下
  • 在 res 下新增一個 xml 目錄,然後建立一個名為:network_security_config.xml 檔案(名字自定) ,內容如下,大概意思就是允許開啟http請求
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config
>

然後在APP的AndroidManifest.xml檔案下的application標籤增加以下屬性

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

參考資料:

https://android-developers.googleblog.com/2018/04/protecting-users-with-tls-by-default-in.html 
https://android-developers.googleblog.com/2018/04/dns-over-tls-support-in-android-p.html