博客主頁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