博客主页java
目前大多数Android端使用的网络框架是OkHttp,经过调用OkHttp提供的自定义Dns服务接口,能够更为优雅地使用HttpDns的服务。segmentfault
OkHttp是一个处理网络请求的开源项目,是Android端最火热的轻量级框架,由移动支付Square公司贡献用于替代HttpUrlConnection和Apache HttpClient。随着OkHttp的不断成熟,愈来愈多的Android开发者使用OkHttp做为网络框架。网络
OkHttp默认使用系统DNS服务InetAddress进行域名解析,但同时也暴露了自定义DNS服务的接口,经过该接口咱们能够优雅地使用HttpDns。app
OkHttp暴露了一个Dns接口,经过实现该接口,咱们能够自定义Dns服务:框架
public class OkHttpDns implements Dns { private static final Dns SYSTEM = Dns.SYSTEM; HttpDnsService httpdns;//httpdns 解析服务 private static OkHttpDns instance = null; private OkHttpDns(Context context) { this.httpdns = HttpDns.getService(context, "account id"); } public static OkHttpDns getInstance(Context context) { if(instance == null) { instance = new OkHttpDns(context); } return instance; } @Override public List<InetAddress> lookup(String hostname) throws UnknownHostException { //经过异步解析接口获取ip String ip = httpdns.getIpByHostAsync(hostname); if(ip != null) { //若是ip不为null,直接使用该ip进行网络请求 List<InetAddress> inetAddresses = Arrays.asList(InetAddress.getAllByName(ip)); Log.e("OkHttpDns", "inetAddresses:" + inetAddresses); return inetAddresses; } //若是返回null,走系统DNS服务解析域名 return Dns.SYSTEM.lookup(hostname); } }
建立OkHttpClient对象,传入OkHttpDns对象代替默认Dns服务:异步
private void okhttpDnsRequest() { OkHttpClient client = new OkHttpClient.Builder() .dns(OkHttpDns.getInstance(getApplicationContext())) .build(); Request request = new Request.Builder() .url("http://www.aliyun.com") .build(); Response response = null; client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); DataInputStream dis = new DataInputStream(response.body().byteStream()); int len; byte[] buff = new byte[4096]; StringBuilder result = new StringBuilder(); while ((len = dis.read(buff)) != -1) { result.append(new String(buff, 0, len)); } Log.d("OkHttpDns", "Response: " + result.toString()); } }); }
以上就是OkHttp+HttpDns实现的所有代码。ide
相比于通用方案,OkHttp+HttpDns有如下两个主要优点:ui
该实践对于Retrofit+OkHttp一样适用,将配置好的OkHttpClient做为Retrofit.Builder::client(OkHttpClient)参数传入便可。this
若是个人文章对您有帮助,不妨点个赞鼓励一下(^_^)url