我想创建一个 custom DNS为我的所有 RetroFit 连接使用 CloudFlare 1.1.1.1 和 1.0.0.1。这应该替换 SYSTEM DNS。
所以我这样做了:
import okhttp3.Dns
import java.net.InetAddress
class CustomDns : Dns {
override fun lookup(hostname: String): List<InetAddress> {
TODO("Not yet implemented")
}
}
对于如何实现抽象查找功能,我有点迷茫。文档说:
Returns the IP addresses of hostname, in the order they will be attempted by OkHttp. If a connection to an address fails, OkHttp will retry the connection with the next address until either a connection is made, the set of IP addresses is exhausted, or a limit is exceeded.abstract fun lookup(hostname:String):List
这是否意味着我创建了一个 HashMap。键将是我的 API 的域,值将包含我的 API 解析到的 IP 地址列表?对我来说似乎不太合适。
有没有办法在这个实现中只使用 1.1.1.1 作为 DNS 解析器?
最佳答案
如果您乐于在 Https 上使用 Dns,那么您可以使用 okhttp-doh 连接到 1.1.1.1
https://github.com/square/okhttp/blob/858939f025068c6d3581338317bba03e63ebd909/okhttp-dnsoverhttps/README.md
val appCache = Cache(File("cacheDir", "okhttpcache"), 10 * 1024 * 1024)
val bootstrapClient = OkHttpClient.Builder().cache(appCache).build()
val dns = DnsOverHttps.Builder().client(bootstrapClient)
.url("https://1.1.1.1/dns-query".toHttpUrl())
.build()
val client = bootstrapClient.newBuilder().dns(dns).build()
其他示例 DNS 提供商 https://github.com/square/okhttp/blob/master/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DohProviders.java如果您想使用常规 DNS,但您需要在应用程序外部的设备上进行这些更改。或者提供你自己的实现,也许是基于 Netty 或类似的实现?
关于android - 如何为 OkHttp3 实现自定义 DNS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65420610/