尝试使用 Retrofit 创建 Android 小部件时出现 UnkownHostException

问题描述 投票:0回答:1

我正在尝试创建一个简单的小部件,仅显示通过 Github 公开的 json 获取的数据。我正在工作室上的模拟器中使用 Retrofit(不知道这是否正确,但我找到了这个),一切都很好,但是当我生成 apk 并将其安装在我的设备上时,它无法工作,并且出现此错误: java.net.UnkownHostException:无法解析主机“host”:没有关联的地址。

我将这些添加到清单中

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

但这仍然不起作用。我什至尝试使用 google.com 但仍然无法解析主机。我可以尝试什么?这是改造问题吗?

这里是改装部分:

@Keep
object RetrofitService {

    private val numbersRetrofit: Retrofit = Retrofit.Builder()
        .baseUrl("https://host.github.io/")
        .client(OkHttpClient())
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    fun getGamesApiService(): GamesApiService {
        return numbersRetrofit.create(GamesApiService::class.java)
    }

}

有什么想法吗? 谢谢

更新: 我也用这个方法检查过:

    private fun isOnline(mgr: ConnectivityManager): Boolean {
        val netInfo = mgr.activeNetworkInfo
        return if (netInfo != null && netInfo.isConnected) {
            true
        } else false
    }

而 netInfo.isConnected 实际上是 false

android kotlin retrofit2 github-pages
1个回答
0
投票

解决方案是在名为

network_security_config.xml
的 xml 文件夹中添加一个文件,其中包含以下内容:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
 </network-security-config>

然后在应用程序标记内的清单中添加此行:

android:networkSecurityConfig="@xml/network_security_config"
© www.soinside.com 2019 - 2024. All rights reserved.