在Android P/9.0下 使用HttpUrlConnection進行http請求會出現以下異常:
java.net.UnknownServiceException: CLEARTEXT communication to ..... not permitted by network security policy
導致這種問題的原因是:
在Android P/9.0 系統的上,http網絡請求是非加密的明文流量,會導致無法連接到網路,,https則不會受影響
解決方法:
(1) 在AndroidManifest.xml 文件,在 application 標籤中添加:
android:usesCleartextTraffic="true"
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/AppTheme">
....
</application>
你也可以用下面方法實現:
在 res 下新增一個 xml 目錄,然後創建一個xml 文件(名字自定),內容如下,意思是允許http網絡權限
我的xml文件爲:network_config.
<?xml version="1.0" encoding="utf-8"?>
<network-config>
<base-config cleartextTrafficPermitted="true" />
</network-config>
在AndroidManifest.xml文件下的application標籤中增加屬性
android:networkSecurityConfig="@xml/network_config"
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:networkSecurityConfig="@xml/network_config"
android:theme="@style/AppTheme">
....
</application>
ok!!! 解決了 你也可以把網絡請求改成 https ,不會出現上面錯誤