android -------- java.net.UnknownServiceException

 最近升級了Android的API版本時 ,導致我的網絡請求失敗了,

出現了這個錯誤 java.net.UnknownServiceException,

 

這個錯誤,我在網上查到這個主要是由於,我們的OkHttp3會默認使用密文傳輸,而我們的代碼中使用Http協議,也就是使用明文傳輸,所以OkHttp3會主動的報錯,然後阻止線程的運行。所以我們現在就是要修改配置文件,使OkHttp3允許使用明文傳輸,或者我們直接使用Https協議。

 

解決方法:

在 res 下新建一個 xml 目錄,然後創建一個名爲:network_security_config.xml 文件 

 

該文件內容如下:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>

    <base-config cleartextTrafficPermitted="true" />

</network-security-config>
然後在 AndroidManifest.xml application 標籤內應用上面的xml配置:
 <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:theme="@style/AppTheme"
        >
</application>

這樣就歐克了

官方文檔: https://developer.android.com/training/articles/security-config

 

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