小公司,免费的Dns解析,有几率遇到域名解析异常(UnknownHostException),但通过IP访问又不方便(比如热备切换后,若IP变化,APP会直接连不上)。这里提供一种域名+IP的解析方法。

Okhttp其实已经提供了Dns解析方法

ApiDns

class ApiDns private constructor() : Dns {
    override fun lookup(hostname: String): List<InetAddress> {
        return try {
            //尝试系统默认解析
            Dns.SYSTEM.lookup(hostname)
        } catch (e: UnknownHostException) {
            //这里的hostname.contains,包含的是服务器域名
            if (hostname.contains("xxxx.com")) {
                "[DNS] $hostname 解析异常,尝试使用IP = $SERVER_IP".errorLog()
                InetAddress.getAllByName(SERVER_IP).asList()
            } else {
                throw e
            }
        }
    }

    companion object {
        // 这个值可以在网络正常时从服务器更新下来,SP、MMKV、SQL等保存在本地,随时更新
        private const val SERVER_IP = "47.xxx.xxx.88"

        val INSTANCE: ApiDns by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { ApiDns() }
    }
}

然后在Okhttp里引用就行了

 Retrofit.Builder()
            .baseUrl(url)
            .client(OkHttpClient.Builder().apply {
                // 主要是这行
                dns(ApiDns.INSTANCE)
                connectTimeout(20, TimeUnit.SECONDS)
                readTimeout(20, TimeUnit.SECONDS)
                writeTimeout(20, TimeUnit.SECONDS)
                addInterceptor(
                    HttpLoggingInterceptor { message ->
                        takeIf { AppUtils.isAppDebug() }?.let { message.networkLog() }
                    }.apply { level = HttpLoggingInterceptor.Level.BODY })
                retryOnConnectionFailure(true)
            }.build())
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiService::class.java)

原帖地址,转载请注明:https://blog.csdn.net/hx7013/article/details/111939812

更多推荐