使用 Network.getAllByName 执行特定于网络的主机名解析 [英] Perform network-specific host name resolutions using Network.getAllByName

查看:88
本文介绍了使用 Network.getAllByName 执行特定于网络的主机名解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ConnectivityManager 文档中,在 bindProcessToNetwork javadoc 中,有以下注释:

In the ConnectivityManager documentation, in bindProcessToNetwork javadoc, there is the following comment :

使用由创建的单独绑定的套接字Network.getSocketFactory().createSocket() 并执行通过 Network.getAllByName 的网络特定主机名解析是首选调用 bindProcessToNetwork.

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 来满足评论的第一部分,但我不知道如何/在哪里使用 Network.getAllByName 来执行主机名称解析.

In OkHttp, there is the setSocketFactory to satisfy the first part of the comment, but I have no idea how/where to use Network.getAllByName to perform the host name resolution.

知道如何执行吗?

推荐答案

好的,我终于知道如何执行了.正如我在我的问题中所说,我使用 OkHttpClient 来设置我的 socketfactory.名称解析也是一样,使用dns(需要OkHttp3).

Ok so I finally find out how to perform that. As I said in my question, I am using OkHttpClient to set my socketfactory. It is the same for the name resolution, using dns (it requires OkHttp3).

OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder()
    .socketFactory(network.getSocketFactory())
    .dns(NetworkDns.getInstance())

我的 NetworkDns 类正在寻找类似的东西

where my NetworkDns class is looking to something like that

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() {
  }
}

这样,当network不为null时,它会在给定的网络上执行主机名解析.

This way, when network is not null, it will perform the host name resolution on the given network.

这篇关于使用 Network.getAllByName 执行特定于网络的主机名解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆