All Products
Search
Document Center

Alibaba Cloud DNS:Best practices for accessing Alibaba Cloud Public DNS SDK on Android apps that use OkHttp

Last Updated:Jun 10, 2022

This topic describes how to access Alibaba Cloud Public DNS SDK on Android apps that use OkHttp.

Overview

OkHttp is an open source lightweight Android framework for processing network requests. It is developed by Square as an alternative to HttpURLConnection and Apache HttpClient. Since its release, OkHttp has gained popularity among Android developers as it matured. OkHttp can provide the following benefits when it is used together with Alibaba Cloud Public DNS SDK for Android:

  • Easy to use. You can access Alibaba Cloud Public DNS simply by implementing the Dns API provided by OkHttp.

  • Widely applicable. No additional configurations are required for HTTPS.

Best practices

By default, OkHttp uses the system's InetAddress to resolve IP addresses for host names. OKHttp also provides the Dns API to perform this operation. OkHttp allows developers to use Alibaba Cloud Public DNS SDK for Android by implementing the Dns API. You do not need to modify the code when you want to establish HTTP connections or even when you specify the Server Name Indication (SNI) for HTTPS connections. Sample code:

mOkHttpClient =new OkHttpClient.Builder()
        .dns(new Dns() {
        @NonNull
        @Override
        public List<InetAddress> lookup(String hostname) {
            Utils.checkNotNull(hostname, "hostname can not be null");
            String ips =dnsResolver.getIPsV4ByHost(url.getHost());
            String[] ipArr = ips.split(";");
            if (0 == ipArr.length) {
                return Collections.emptyList();
            }
           List<InetAddress> inetAddressList = new ArrayList<>(ipArr.length);
           for (String ip : ipArr) {
               if ("0".equals(ip)) {
                   continue;
                }
           }
           try {
                InetAddress inetAddress =InetAddress.getByName(ip);
                inetAddressList.add(inetAddress);
            } catch (UnknownHostException ignored) {
         }
      }
      return inetAddressList;
   }
})
.build();
Notice

After you implement the Dns API, Alibaba Cloud Public DNS can receive all network requests processed by the OkHttpClient instance. If a small number of domain names need to be resolved by Alibaba Cloud Public DNS, we recommend that you filter the network requests before you implement the Dns API to use Alibaba Cloud public DNS SDK for Android.

Access Alibaba Cloud Public DNS SDK for Android

  • Implement the API for a custom DNS resolution service

OkHttp provides a Dns API for developers to configure DNS resolution services based on business requirements. For the complete sample code of accessing Alibaba Cloud Public DNS SDK on Android apps that use OkHttp, see the source code for a demo project.

  1. Create a new class in the project directory to implement the Dns API.

  2. Implement the Dns API and override the lookup function with API operations to resolve domain names. For more information about the API operations, see SDK for Android developer guide.

  public class OkHttpDns implements Dns {

    private static OkHttpDns instance;
    private static Object lock = new Object();
    private DNSResolver mDNSResolver = DNSResolver.getInstance();

    private OkHttpDns() {
    }

    public static OkHttpDns getInstance() {
        if (null == instance) {
            synchronized (lock) {
                if (instance == null) {
                    instance = new OkHttpDns();
                }
            }
        }
        return instance;
    }

    @Override
    public List<InetAddress> lookup(@NonNull String hostname) throws UnknownHostException {
        // Call the API operation in Alibaba Cloud Public DNS SDK for Android to resolve a domain name.
        String ip = mDNSResolver.getIPV4ByHost(hostname);
        Log.d(TAG, "mDnsCache IP: " + ip);

        if (ip != null) {
            // If the returned ip value is not null, directly use the IP address to send network requests.
            return Arrays.asList(InetAddress.getAllByName(ip));
        }
        // If null is returned, use the system DNS service to resolve the domain name.
        return Dns.SYSTEM.lookup(hostname);
    }
}

  • Create an OkHttpClient instance

public void okhttpDnsRequest(String url, final Handler mHandler) {
        OkHttpClient client = new OkHttpClient.Builder()
                .dns(OkHttpDns.getInstance())
                .build();

        Request request = new Request.Builder()
                .url(url)
                .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));
                }

                String resultInfo = result.toString();
                Log.d("OkHttpDns", "Response: " + resultInfo);
             }
        });
    }
Notice

  1. This topic provides references only for scenarios where OKHttp and Alibaba Cloud Public DNS SDK for Android are used together.

  2. For information about how to use Alibaba Cloud Public DNS SDK for Android and the DNS resolution service, see SDK for Android developer guide.

  3. For the complete sample code of accessing Alibaba Cloud Public DNS SDK on Android apps that use OkHttp, see the source code for a demo project.