[关闭]
@act262 2017-06-27T11:49:06.000000Z 字数 1189 阅读 4780

设置OkHttp的DNS域名解析

Android


使用OkHttp的Dns可以自由配置想要的Dns解析,可以用来在不同环境下指定Host的指向。
也可以定向解析一些IP,可以加速网络请求。

  1. /**
  2. * 预置DNS解析,默认使用系统的{@link Dns#SYSTEM}
  3. */
  4. public class DnsFactory {
  5. public static Dns getDns() {
  6. switch (Environment.getType()) {
  7. case Environment.TYPE_TEST:
  8. return new DevDns();
  9. case Environment.TYPE_PRE_RELEASE:
  10. return new PreReleaseDns();
  11. case Environment.TYPE_ONLINE:
  12. default:
  13. return Dns.SYSTEM;
  14. }
  15. }
  16. // 日常测试环境DNS
  17. private static class DevDns implements Dns {
  18. @Override
  19. public List<InetAddress> lookup(String hostname) throws UnknownHostException {
  20. return SYSTEM.lookup(hostname);
  21. }
  22. }
  23. // 预发环境DNS
  24. private static class PreReleaseDns implements Dns {
  25. @Override
  26. public List<InetAddress> lookup(String hostname) throws UnknownHostException {
  27. // hostname ip 配置白名单,手动设置Host对应的IP
  28. if ("xxxx".equals(hostname)
  29. || "xxxx".equals(hostname)
  30. || "xxxx".equals(hostname)
  31. || "xxxx".equals(hostname)) {
  32. InetAddress byAddress = InetAddress.getByAddress(hostname, new byte[]{xx,xx,xx,xx});
  33. return Collections.singletonList(byAddress);
  34. } else {
  35. return SYSTEM.lookup(hostname);
  36. }
  37. }
  38. }
  39. }

在OkHttpClient全局配置时设置上Dns解析器

  1. OkHttpClient.Builder builder = new OkHttpClient.Builder()
  2. .connectTimeout(20, TimeUnit.SECONDS)
  3. .readTimeout(30, TimeUnit.SECONDS)
  4. .writeTimeout(30, TimeUnit.SECONDS)
  5. // 根据具体开发环境设置DNS解析器
  6. builder.dns(DnsFactory.getDns());
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注