一、前言
爲保證用戶數據和設備的安全,Google 針對下一代 Android 系統(Android P) 的應用程序,將要求默認使用加密連接,這意味着 Android P 將禁止 App 使用所有未加密的連接。因此運行 Android P 系統的安卓設備無論是接收或者發送流量,未來都不能明碼傳輸,需要使用下一代(Transport Layer Security)傳輸層安全協議,而 Android Nougat 和 Oreo 則不受影響。
二、問題
在Android P 系統的設備上,如果應用使用的是 非加密的明文流量 的 http 網絡請求,則會導致該應用無法進行網絡請求,https 則不會受影響。同樣地,如果應用嵌套了 webview,webview 也只能使用 https 請求。
在 Android P 使用 HttpUrlConnection 進行 http 請求會出現以下異常:
W/System.err: java.io.IOException: Cleartext HTTP traffic to **** not permitted
使用 OKHttp 請求則出現:
java.net.UnknownServiceException: CLEARTEXT communication to **** not permitted by network security policy
三、解決方案
針對這種情況,有以下四種解決方案:
-
APP 改用 https 請求。條件允許的話,建議使用,以增強安全性。
-
Android 編譯的 targetSdkVersion 改爲27以下。因爲是高版本纔出現的,那可以降維處理。
-
在 AnroidManifest.xml 中的 application 添加設置項:
<application android:usesCleartextTraffic=“true”> -
添加網絡安全配置。
在 res 的 xml 目錄下,新建一個 network_config.xml 文件(名稱隨便取):
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
然後在 AnroidManifest.xml 中的 application 添加指向該文件的設置項:
<application
...
android:networkSecurityConfig="@xml/network_config"
...
/>
5.
非Activity-Context啓動Activity,現在強制執行 FLAG_ACTIVITY_NEW_TASK 要求,Apache HTTP 客戶端棄用,影響採用非標準 ClassLoader 的應用。
在項目中用到了 Apache HTTP client 的相關類,就會拋出找不到這些類的錯誤。這是因爲官方已經在 Android P 的啓動類加載器中將其移除,如果仍然需要使用 Apache HTTP client.
Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.protocol.BasicHttpContext" on path: DexPathList”
在 AnroidManifest.xml 中的 application 添加:
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />