解決okhttp或者retrofit出現UnknownHostException的問題

首先確認你的設備能否解析該域名,可以直接ping這個域名,如果能ping通則代表設備所處的網絡是沒有問題的,如果不能ping通可以嘗試接入阿里雲或者其他雲服務廠商提供的http dns服務,或者檢查一下網絡狀況。
在排除掉以上問題以後,檢查一下是否添加了網絡訪問權限

<uses-permission android:name="android.permission.INTERNET" />

如果網絡權限也添加了,仍然出現該問題,確認是否使用的http協議而不是https協議,如果是http協議的話,需要在AndroidManifest中的application標籤添加一個usesCleartextTraffic屬性

 <application
        android:name=".xx.xxx"
        android:allowBackup="true"
        android:icon="@drawable/app_logo"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/ImageTranslucentTheme">
       
 </application>

當然也可以把你的targetSDK改到28以下,或者升級到https協議,從安全的角度來看升級到https協議是最好的。

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