使用 Network.getAllByName 执行特定于网络的主机名解析
Perform network-specific host name resolutions using Network.getAllByName
在 ConnectivityManager 文档中,在 bindProcessToNetwork
javadoc 中,有以下注释:
Using individually bound Sockets created by
Network.getSocketFactory().createSocket() and performing
network-specific host name resolutions via Network.getAllByName is
preferred to calling bindProcessToNetwork.
在OkHttp中,有setSocketFactory
来满足评论的第一部分,但我不知道how/where使用Network.getAllByName
来执行主机名解析。
知道如何执行吗?
好的,所以我终于找到了如何执行它。
正如我在问题中所说,我正在使用 OkHttpClient
来设置我的 socketfactory。名称解析也是一样,使用dns
(需要OkHttp3)。
OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder()
.socketFactory(network.getSocketFactory())
.dns(NetworkDns.getInstance())
我的 NetworkDns class 正在寻找类似的东西
public class NetworkDns implements Dns {
private static NetworkDns sInstance;
private Network mNetwork;
public static NetworkDns getInstance() {
if (sInstance == null) {
sInstance = new NetworkDns();
}
return sInstance;
}
public void setNetwork(Network network) {
mNetwork = network;
}
@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
if (mNetwork != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return Arrays.asList(mNetwork.getAllByName(hostname));
}
return SYSTEM.lookup(hostname);
}
private NetworkDns() {
}
}
这样,当网络不为空时,它将在给定网络上执行主机名解析。
在 ConnectivityManager 文档中,在 bindProcessToNetwork
javadoc 中,有以下注释:
Using individually bound Sockets created by Network.getSocketFactory().createSocket() and performing network-specific host name resolutions via Network.getAllByName is preferred to calling bindProcessToNetwork.
在OkHttp中,有setSocketFactory
来满足评论的第一部分,但我不知道how/where使用Network.getAllByName
来执行主机名解析。
知道如何执行吗?
好的,所以我终于找到了如何执行它。
正如我在问题中所说,我正在使用 OkHttpClient
来设置我的 socketfactory。名称解析也是一样,使用dns
(需要OkHttp3)。
OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder()
.socketFactory(network.getSocketFactory())
.dns(NetworkDns.getInstance())
我的 NetworkDns class 正在寻找类似的东西
public class NetworkDns implements Dns {
private static NetworkDns sInstance;
private Network mNetwork;
public static NetworkDns getInstance() {
if (sInstance == null) {
sInstance = new NetworkDns();
}
return sInstance;
}
public void setNetwork(Network network) {
mNetwork = network;
}
@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
if (mNetwork != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return Arrays.asList(mNetwork.getAllByName(hostname));
}
return SYSTEM.lookup(hostname);
}
private NetworkDns() {
}
}
这样,当网络不为空时,它将在给定网络上执行主机名解析。