Android使用Retrofit報錯java.net.UnknownServiceException

由於Retrofit底層使用是基於OkHttp3的,但是OkHttp3會默認使用密文傳輸,代碼中使用Http協議,也就是使用明文傳輸,所以OkHttp3會主動的報錯,然後阻止線程的運行。所以會直接報錯,但是這個報錯並不是在所有型號的手機上都會發生的,比如:一加3正常運行,華爲手機無法連接服務器。
解決辦法
解決辦法有兩種,分別爲:

  1. 修改配置文件,使OkHttp3允許使用明文傳輸。
  2. 直接使用Https協議。
    我們這裏主要介紹一下第一種方法:
    在 res 下新建一個 xml 目錄,然後創建一個名爲:network_security_config.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:name=".App"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:networkSecurityConfig="@xml/network_security_config"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:theme="@style/AppTheme">
</application>

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