如何为 OkHttp3 实现自定义 DNS
How to implement a custom DNS for OkHttp3
我想创建一个 custom DNS 以将 CloudFlare 1.1.1.1 和 1.0.0.1 用于我所有的 RetroFit 连接。这应该替换 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 解析器?
如果您愿意使用 Dns over Https,那么您可以使用 okhttp-doh 连接到 1.1.1.1
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或类似的实现?
我想创建一个 custom DNS 以将 CloudFlare 1.1.1.1 和 1.0.0.1 用于我所有的 RetroFit 连接。这应该替换 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 解析器?
如果您愿意使用 Dns over Https,那么您可以使用 okhttp-doh 连接到 1.1.1.1
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或类似的实现?