@act262
2017-06-27T11:49:06.000000Z
字数 1189
阅读 5320
Android
使用OkHttp的Dns可以自由配置想要的Dns解析,可以用来在不同环境下指定Host的指向。
也可以定向解析一些IP,可以加速网络请求。
/*** 预置DNS解析,默认使用系统的{@link Dns#SYSTEM}*/public class DnsFactory {public static Dns getDns() {switch (Environment.getType()) {case Environment.TYPE_TEST:return new DevDns();case Environment.TYPE_PRE_RELEASE:return new PreReleaseDns();case Environment.TYPE_ONLINE:default:return Dns.SYSTEM;}}// 日常测试环境DNSprivate static class DevDns implements Dns {@Overridepublic List<InetAddress> lookup(String hostname) throws UnknownHostException {return SYSTEM.lookup(hostname);}}// 预发环境DNSprivate static class PreReleaseDns implements Dns {@Overridepublic List<InetAddress> lookup(String hostname) throws UnknownHostException {// hostname ip 配置白名单,手动设置Host对应的IPif ("xxxx".equals(hostname)|| "xxxx".equals(hostname)|| "xxxx".equals(hostname)|| "xxxx".equals(hostname)) {InetAddress byAddress = InetAddress.getByAddress(hostname, new byte[]{xx,xx,xx,xx});return Collections.singletonList(byAddress);} else {return SYSTEM.lookup(hostname);}}}}
在OkHttpClient全局配置时设置上Dns解析器
OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS)// 根据具体开发环境设置DNS解析器builder.dns(DnsFactory.getDns());