All Products
Search
Document Center

Alibaba Cloud DNS:SDK for Android developer guide

Last Updated:Apr 09, 2024

This topic describes how to develop Alibaba Cloud Public DNS SDK for Android and use the SDK to access Alibaba Cloud Public DNS.

1. Overview

Alibaba Cloud Public DNS SDK is developed by Alibaba Cloud to provide a Domain Name System (DNS) resolution service for mobile developers.

The SDK allows mobile developers to easily access Alibaba Cloud Public DNS in their Android apps. This prevents DNS resolution errors and implements precise scheduling of DNS queries at a low cost. The demo project source code provides you with an example on how to integrate the SDK with an Android app and how to use Alibaba Cloud Public DNS in the Android app.

The SDK of the current version encapsulates the JSON API for DoH of Alibaba Cloud Public DNS. The SDK provides Java function interfaces for Android apps to perform DNS resolution and can cache DNS resolution results based on time-to-live (TTL) and least recently used (LRU) policies in an effective manner. The SDK provides the following benefits based on the features of Alibaba Cloud Public DNS:

  • Ease of use

    To use Alibaba Cloud Public DNS, you need to only integrate the SDK with your app. This way, you can use the DNS resolution service in an easier and more convenient manner.

  • DNS resolution without delay

    The SDK implements the LRU caching algorithm so that the IP addresses obtained from DNS resolution are cached on your on-premises server. The SDK also automatically updates the cached data and deletes expired data based on TTL. This way, the cached data remains valid, and DNS resolution can be performed without delay.

2. Use the SDK

  • Log on to the Alibaba Cloud DNS console. In the left-side navigation pane, click Public DNS. On the Public DNS page, activate Alibaba Cloud Public DNS. The Overview tab displays the unique account ID that is automatically generated for your Alibaba Cloud account. You can use Alibaba Cloud Public DNS in your app based on the account ID.

  • Then, specify the AccessKey ID and AccessKey Secret parameters for authentication in the AndroidManifest.xml file in your project directory.

  • Integrate the SDK with your app project.

2.1 Integrate the SDK AAR package with the project

Click here to obtain the SDK AAR package alidns_android_sdk.aar of Public DNS in the Alibaba Cloud DNS console. Decompress the package to the libs directory of your project to install the SDK. Then, you can use the SDK.

2.2 Add the Maven repository to the build.gradle file

Add the following code to the build.gradle file:

allprojects {
  repositories {
    maven {
      url 'https://maven.aliyun.com/repository/public/'
    }
    mavenLocal()
    mavenCentral()
  }
}

Add the following file information that you want to reference:

dependencies {
     implementation 'com.alibaba.pdns:alidns-android-sdk:2.2.0'
     implementation 'com.google.code.gson:gson:2.8.5'
}
Note

You can use either of the preceding methods to integrate the SDK with your project.

2.3 App initialization

public class DnsCacheApplication extends Application{

    private String accountID="***"; // Set the account ID that is used to access the SDK in the Alibaba Cloud DNS console.
    private static final String TAOBAO_HOST_NAME = "www.taobao.com";// Replace www.taobao.com with the domain name that you want to preload.
    private static final String ALIYUN_HOST_NAME = "www.aliyun.com"; // Replace www.aliyun.com with the domain name that you want to preload.
    private static final int CACHE_MAX_NUMBER=100; // Set the maximum number of DNS resolution results that can be cached. The default value is 100.
    private static final int MAX_NEGATIVE_CACHE = 30; // Set the maximum TTL period for negative caching. The default value is 30. Unit: seconds. 
    private static final int MAX_TTL_CACHE = 1 * 60 * 60; // Set the maximum TTL period for caching. The default value is 3600. Unit: seconds.

    @Override
    public void onCreate() {
       super.onCreate();
       DNSResolver.Init(this, accountID);    // Set the account ID that is used to access the SDK in the Alibaba Cloud DNS console.
       DNSResolver.setEnableShort(false); // Specify whether to enable the short mode. The default value is false, which indicates that the short mode is not enabled.
       DNSResolver.setEnableIPv6(false);   // Specify whether to enable IPv6 access. The default value is false, which indicates that IPv6 access is not enabled.
       DNSResolver.setEnableCache(true); // Specify whether to enable caching. The default value is true, which indicates that caching is enabled.
       DNSResolver.setEnableSpeedTest(false); // Specify whether to enable connection speed testing of IP addresses. The default value is false, which indicates that this feature is not enabled.
       DNSResolver.setEnableSchedulePrefetch(true); // Specify whether to enable the scheduled update of expired cache data. The default value is true, which indicates that this feature is enabled.
       DNSResolver.setMaxTtlCache(MAX_TTL_CACHE); // Set the maximum TTL period for caching. The default value is 3600. Unit: seconds.
       DNSResolver.setSpeedPort(DNSResolver.PORT_80); // Set the port number for IP socket detection. The default port number is 80.
       DNSResolver.setMaxNegativeCache(MAX_NEGATIVE_CACHE); // Set the maximum TTL period for negative caching. The default value is 30. Unit: seconds.
       DNSResolver.setSchemaType(DNSResolver.HTTPS); // Specify whether the access protocol is HTTP or HTTPS.
       DNSResolver.getInstance().setMaxCacheSize(CACHE_MAX_NUMBER); // Set the maximum number of DNS resolution results that can be cached. The default value is 100.
       DNSResolver.getInstance().preLoadDomains(new String[]{TAOBAO_HOST_NAME,ALIYUN_HOST_NAME}); // Specify the domain names that you want to pre-resolve and replace the domain names that you want to preload with the domain names that you want to use Alibaba Cloud Public DNS to resolve.
    }
}

When you use the SDK to access Alibaba Cloud Public DNS, we recommend that you integrate the SDK into the Application class of your Android app.

Note

DNSResolver is the core class of Alibaba Cloud Public DNS SDK. DNSResolver encapsulates the JSON API for DoH provided by Alibaba Cloud Public DNS to resolve the desired domain name to the corresponding IP addresses.

When you use the SDK for an Android project, make sure that you have configured the following access permissions:

<!--Permissions that must be configured-->
   <uses-permission android:name="android.permission.INTERNET"/>
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Usage notes:

(1) If a device that runs Android 9.0 sends an HTTP request, the error message "cleartext HTTP traffic no permitted" is returned.

  • Cause: By default, plaintext network access is disabled on Android devices from Android 9.0 (API level 28 for Android SDK Platform).

  • Solution

Add the following configuration to the <application> section in the AndroidManifest.xml file of your Android app:

android:usesCleartextTraffic="true"

<application
        android:name=".DnsCacheApplication"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">

(2) If you use a device that runs Android 9.0, the error message "Didn't find class BasicHttpParams" is returned.

  • Cause: Apache HttpClient is no longer supported.

Google has removed support for Apache HttpClient as of Android 6.0. In Android 9.0 and later, org.apache.http.legacy is removed from bootclasspath.

This modification does not affect most apps whose taskVersion is earlier than Android 9.0. However, if the Apache HTTP interface is still used or the referenced lib package uses the Apache HTTP interface when you use an app for which the value of taskVersion is greater than Android 9.0, the error message "Didn't find class BasicHttpParams" is returned.

  • Solution

Add the following configuration to the <application> section in the AndroidManifest.xml file of your Android app:

<uses-library android:name="org.apache.http.legacy" android:required="false"/>

(3) You can use SDK 2.0 or later to enable authentication to prevent user identities from being used by unauthorized third parties.

You can enable the authentication feature only after you set the parameters contained in the following configuration. To enable this feature, you must create an AccessKey ID and an AccessKey secret in the Alibaba Cloud DNS console. For more information, see Service authentication. You can add the following configuration to the AndroidManifest.xml file of your Android app and set the parameters:

   <meta-data
            android:name="com.alibaba.pdns.ACCESS_KEY_ID"
            android:value="The AccessKey ID that is generated when you register your Android app in the Alibaba Cloud Management Console."/>

   <meta-data
            android:name="com.alibaba.pdns.ACCESS_KEY_SECRET"
            android:value="The AccessKey secret that is generated when you register your Android app in the Alibaba Cloud Management Console."/>

(4) The SDK starts to use Java Native Interface (JNI) from version 2.1.9. Therefore, you must configure Native Development Kit (NDK) in the development environment of your app project.

  • Add the installation directory of NDK to the local.properties file in the root directory of the app project.

ndk.dir=...\\ndk\\21.4.7075529 ... The local directory of NDK.

  • Add the following configuration to the gradle.properties file in the root directory of the app project:

android.useDeprecatedNdk = true

If you have configured NDK for your app project, skip this step.

(5) To use the SDK in a more effective manner, we recommend that you set the Java Development Kit (JDK) version to 1.8 and the NDK version to 21.4.7075529 when you compile the app.

2.4.1 Initialize the service

Alibaba Cloud Public DNS SDK uses the DNSResolver class to encapsulate the service requests and local caches of Alibaba Cloud Public DNS. You can use DNSResolver.Init(this,accountID) to initialize the SDK to access Alibaba Cloud Public DNS. The value of accountID is the unique ID that the server automatically generates when you register your Alibaba Cloud account in the Alibaba Cloud DNS console.

2.4.2 Configure domain names that you want to pre-resolve

When you initialize your Android app, you can register domain names that you may use with Alibaba Cloud Public DNS SDK so that the SDK can resolve the domain names in advance. This reduces the delay of requests during subsequent DNS resolution. The following code shows how to configure domain names that you want to pre-resolve.

  • Specify IPv6 or IPv4 domain names that you want to preload

// Specify the domain names that you want to pre-resolve and replace the domain names that you want to preload with the domain names that you want to use Alibaba Cloud Public DNS to resolve.
DNSResolver.getInstance().preLoadDomains(DNSResolver.QTYPE_IPV4,new String[]{...})

DNSResolver.QTYPE_IPV4  Obtain the IPv4 record type that corresponds to the pre-resolved domain names.
DNSResolver.QTYPE_IPV6  Obtain the IPv6 record type that corresponds to the pre-resolved domain names.

  • Automatically match and preload IPv6 or IPv4 domain names for resolution based on the current network

DNSResolver.getInstance().preLoadDomains(domains)
Important

When you configure a pre-resolution interface, an asynchronous network request is triggered in real time. You must make sure that the code logic has the necessary initialization settings when the pre-resolution interface is called.

2.4.3 Specify whether to use the IPv6 addresses of servers

Alibaba Cloud Public DNS supports IPv4 and IPv6 dual-stack access. You can set DNSResolver.setEnableIPv6(boolean enable) to determine whether to use IPv6 addresses. If you set DNSResolver.setEnableIPv6(boolean enable) to true, IPv6 addresses are used to access the server interface. If you set DNSResolver.setEnableIPv6(boolean enable) to false, IPv4 addresses are used to access the server interface. If you do not set DNSResolver.setEnableIPv6(boolean enable), IPv4 addresses are used for access by default. If IPv6 addresses are used for access, the system automatically switches to IPv4 addresses when Alibaba Cloud Public DNS becomes inaccessible. In this case, a maximum of three access retries are allowed.

2.4.4 Specify whether to enable the short mode

The data returned by the JSON API for DoH of Alibaba Cloud Public DNS can be in the JSON format or a simple array of IP addresses. You can set DNSResolver.setEnableShort (boolean enable) to enable or disable the short mode. If you do not set DNSResolver.setEnableShort (boolean enable), the short mode is disabled by default.

The following sample code shows the configuration of the short mode:

DNSResolver.setEnableShort (true); // The default value is false. If you do not set this parameter, the default value is used.
Important

In short mode, the SDK calls Alibaba Cloud Public DNS to return a simple array of IP addresses. This reduces the amount of data returned and is suitable for scenarios in which heavy network traffic is not allowed.

2.4.5 Set the maximum number of DNS resolution results that can be cached

DNSResolver.getInstance().setMaxCacheSize(CACHE_MAX_NUMBER); // Set the maximum number of DNS resolution results that can be cached. The default value is 100.

You can set the CACHE_MAX_NUMBER parameter based on your business requirements.

2.4.6 Set the maximum TTL period for caching

DNSResolver.setMaxTtlCache(MAX_TTL_CACHE);// Set the maximum TTL period for caching. The default value is 3600. Unit: seconds.

2.4.7 Set the server access protocol

DNSResolver.setSchemaType(DNSResolver.HTTPS); // Set the server access protocol. The default access protocol is HTTP.

DNSResolver.HTTP indicates that HTTP is used to access the server interface.

DNSResolver.HTTPS indicates that HTTPS is used to access the server interface.

2.4.8 Specify whether to enable the caching feature

DNSResolver.setEnableCache(true); // Specify whether to enable the caching feature. This feature is enabled by default.

If setEnableCache is set to true, the caching feature is enabled. If setEnableCache is set to false, the caching feature is disabled.

2.4.9 Specify whether to enable connection speed testing of IP addresses

DNSResolver.setEnableSpeedTest(false); // Specify whether to enable connection speed testing of IP addresses. This feature is disabled by default.

If setEnableSpeedTest is set to true, this feature is enabled. If setEnableSpeedTest is set to false, this feature is disabled.

2.4.10 Specify the port number in the socket for connection speed testing of IP addresses

DNSResolver.setSpeedPort(DNSResolver.PORT_80)

You can specify the port number in the socket for connection speed testing of IP addresses. The default port number is 80.

2.4.11 Specify whether to enable domain name caching based on ISP networks

DNSResolver.setIspEnable(true);// Specify whether to enable domain name caching based on ISP networks.

You can enable domain name caching based on Internet service provider (ISP) networks. If setIspEnable is set to true, the cached DNS resolution results are separately stored based on network environments. If setIspEnable is set to false, the same cached DNS resolution results are used for different networks.

2.4.12 Set the maximum TTL period for negative caching

DNSResolver.setMaxNegativeCache(MAX_NEGATIVE_CACHE);// Set the maximum TTL period for negative caching. The default value is 30. Unit: seconds.

You can set the maximum TTL period for negative caching based on your business requirements.

2.4.13 Specify whether to enable the scheduled update of expired cache data

If the caching feature is enabled, you can enable the scheduled update of expired cache data. After the scheduled update of expired cache data is enabled, the SDK automatically replaces the expired cache data with new data at an interval of 1 minute. This way, data in the cache can be updated in a timely manner, but the number of times DNS resolution is performed, and the traffic consumption of clients may increase.

DNSResolver.setEnableSchedulePrefetch(true); // Specify whether to enable the scheduled update of expired cache data. The default value is true, which indicates that this feature is enabled.

3. Anti-obfuscation configuration

   -keep class com.alibaba.pdns.** {*;}

4. Service API operations

 /**
   * Automatically detect the IP address type that is supported by the current network environment, such as IPv4-only, IPv6-only, or IPv4/IPv6 dual-stack, to obtain the DNS resolution result of the domain name.
   * If DNS resolution results exist in the cache and do not expire, the cached DNS resolution results are returned.
   * If no cached data exists or the cached data expires, a recursive DNS request is sent to DNS servers to obtain a DNS resolution result which is then returned to clients and cached.
   *
   * @param host The domain name that you want to resolve.
   * @return Obtain the optimal array of IP addresses based on the current network environment.
   */
 public String[] getIpsByHost(String host)


  /**
   * Automatically detect the IP address type that is supported by the current network environment, such as IPv4-only, IPv6-only, or IPv4/IPv6 dual-stack, to preload the domain names that you want to resolve.
   * After you start your app, you can call this operation to cache DNS resolution results. This accelerates subsequent DNS resolution.
   *
   * @param domains The domain names that you want to preload.
   */
   public void preLoadDomains(final String[] domains)


 /**
   * Automatically detect the IP address type that is supported by the current network environment, such as IPv4-only, IPv6-only, or IPv4/IPv6 dual-stack, to obtain the array of IP addresses from the cache after the domain name is resolved.
   * If no IP address array exists in the cache, null is returned. Then, an asynchronous query is triggered, and the query results are stored in the cache.
   * If cached DNS resolution results expire, the expired DNS resolution results are returned to clients first if allowed. Then, the cached DNS resolution results are asynchronously updated.
   * If the expired DNS resolution results in the cache are not allowed to be returned, null is returned first. Then, the cached DNS resolution results are asynchronously updated.
   *
   * @param host The domain name that you want to query, such as www.taobao.com.
   * @param isAllowExp Specify whether to return the DNS resolution results if the domain name expires.
   * @return Obtain the array of IP addresses from the cache after the domain name is resolved.
   */
    public String[] getIpsByHostFromCache(String host, boolean isAllowExp)
   

 /**
  * Obtain the DomainInfo object array in the IPv4 records that correspond to a specific URL.
  * If DNS resolution results exist in the cache and do not expire, the cached DNS resolution results are returned.
  * If no cached data exists or the cached data expires, a recursive DNS request is sent to DNS servers to obtain a DNS resolution result which is then returned to clients and cached.
  *
  * @param url Example: http://www.taobao.com
  * @return The DomainInfo object array in the IPv4 records that correspond to the URL is returned.
  */
    public DomainInfo[] getIPsV4DInfoByUrl(String url) 

  Note: The URL in the DomainInfo object array is the URL in which the host field is automatically replaced by a specific IP address. You do not need to manually replace the host field in the URL. 

 /**
   * Obtain the DomainInfo object array in the IPv6 records that correspond to a specific URL.
   * If DNS resolution results exist in the cache and do not expire, the cached DNS resolution results are returned.
   * If no cached data exists or the cached data expires, a recursive DNS request is sent to DNS servers to obtain a DNS resolution result which is then returned to clients and cached.
   * 
   * @param url Example: http://m.taobao.com
   * @return The DomainInfo object array in the IPv6 records that correspond to the URL is returned.
   */
    public DomainInfo[] getIPsV6DInfoByUrl(String url) 


  /**
    * Obtain the DomainInfo object in the IPv4 records that correspond to a specific URL.
    * If DNS resolution results exist in the cache and do not expire, the cached DNS resolution results are returned.
    * If no cached data exists or the cached data expires, a recursive DNS request is sent to DNS servers to obtain a DNS resolution result which is then returned to clients and cached.
    *
    * @param url Example: http://m.taobao.com
    * @return A DomainInfo object in the IPv4 records that correspond to the URL is returned.
    */
     public DomainInfo getIPV4DInfoByUrl(String url) 


 /**
    * Obtain a DomainInfo object in the IPv6 records that correspond to a specific URL.
    * If DNS resolution results exist in the cache and do not expire, the cached DNS resolution results are returned.
    * If no cached data exists or the cached data expires, a recursive DNS request is sent to DNS servers to obtain a DNS resolution result which is then returned to clients and cached.
    *
    * @param url Example: http://www.taobao.com
    * @return A DomainInfo object in the IPv6 records that correspond to the URL is returned.
    */
    public DomainInfo getIPV6DInfoByUrl(String url) 

   Note: The returned DomainInfo object encapsulates the following attributes:

  /**
   * The auto-increment ID of the access domain name.
    */
    public String id = null;

   /**
    * The available URL in which the host field is replaced by an IP address.
    */
     public String url = null;

    /**
    * The service name that needs to be contained in the header of the HTTP request.
    */
    public String host = "";

   /**
    * The returned content body.
    */
   public String data = null;

   /**
    * The start time of the request.
    */
   public String startTime = null;

   /**
    * The end time of the request. If the request times out, the value is null.
    */
   public String stopTime = null; 

   /**
   * The status code returned by the server, such as 200, 404, or 500. 
   */
   public String code = null;

   /**
    * Obtain the array of IPv4 records that correspond to a specific hostname.
    * If DNS resolution results exist in the cache and do not expire, the cached DNS resolution results are returned.
    * If no cached data exists or the cached data expires, a recursive DNS request is sent to DNS servers to obtain a DNS resolution result which is then returned to clients and cached.
    *
    * @param hostName Example: www.taobao.com
    * @return The array of IPv4 addresses that correspond to the hostname is returned.
    */
  public  String[] getIPsV4ByHost(String hostName) 

   /**
    * Obtain the array of IPv6 records that correspond to a specific hostname.
    * @param hostName Example: www.taobao.com
    * @return The array of IPv6 addresses that correspond to the hostname is returned.
    */
  public String[] getIPsV6ByHost(String hostName) 

  /**
    * Obtain an IPv4 record that corresponds to a specific hostname.
    * If DNS resolution results exist in the cache and do not expire, the cached DNS resolution results are returned.
 		* If no cached data exists or the cached data expires, a recursive DNS request is sent to DNS servers to obtain a DNS resolution result which is then returned to clients and cached.
  
    * @param hostName Example: www.taobao.com
    * @ return A random IPv4 address in the set of IPv4 addresses that correspond to the hostname is returned. If connection speed testing of IP addresses is enabled, the optimal IPv4 address is returned.
    */
  public String getIPV4ByHost(String hostName) 

   /**
    * Obtain an IPv6 record that corresponds to a specific hostname.
    * If DNS resolution results exist in the cache and do not expire, the cached DNS resolution results are returned.
    * If no cached data exists or the cached data expires, a recursive DNS request is sent to DNS servers to obtain a DNS resolution result which is then returned to clients and cached.
  
    * @param hostName Example: www.taobao.com
    * @return A random IPv6 address in the set of IPv6 addresses that correspond to the hostname is returned. If connection speed testing of IP addresses is enabled, the optimal IPv6 address is returned.
    */
 public String getIPV6ByHost(String hostName) 

   /**
     * Obtain the IP address array of the IPv4 record type from the cache after the domain name is resolved.
     * If no IP address array exists in the cache, null is returned. Then, an asynchronous query is triggered, and the query results are stored in the cache.
     * If cached DNS resolution results expire, the expired DNS resolution results are returned to clients first if allowed. Then, the cached DNS resolution results are asynchronously updated.
     * If the expired DNS resolution results in the cache are not allowed to be returned, null is returned first. Then, the cached DNS resolution results are asynchronously updated.
     *
     * @param host The domain name that you want to query, such as www.taobao.com.
     * @param isAllowExp Specify whether to return the DNS resolution results if the domain name expires.
     * @return The IP address array of the IPv4 record type in the cache is returned after the domain name is resolved.
     */
    private String[] getIpv4ByHostFromCache(String host , boolean isAllowExp)

    /**
     * Obtain the IP address array of the IPv6 record type from the cache after the domain name is resolved.
     * If no IP address array exists in the cache, null is returned. Then, an asynchronous query is triggered, and the query results are stored in the cache.
     * If cached DNS resolution results expire, the expired DNS resolution results are returned to clients first if allowed. Then, the cached DNS resolution results are asynchronously updated.
     * If the expired DNS resolution results in the cache are not allowed to be returned, null is returned first. Then, the cached DNS resolution results are asynchronously updated.
     *
     * @param host The domain name that you want to query, such as www.taobao.com.
     * @param isAllowExp Specify whether to return the DNS resolution results if the domain name expires.
     * @return The IP address array of the IPv6 record type in the cache is returned after the domain name is resolved.
     */
    private String[] getIpv6ByHostFromCache(String host , boolean isAllowExp)      

   /**
     * Preload a domain name for resolution. 
     * After you start your app, you can call this operation to cache DNS resolution results. This accelerates subsequent DNS resolution.
     *
     * @param qType The type of IP addresses that you want to preload, such as IPv4 or IPv6.
     * @param domains The domain names that you want to preload.
     */
    public void preLoadDomains(String qType, final String[] domains)

   /**
     * Obtain the statistics on successful queries and failed queries of Alibaba Cloud Public DNS.
     *
     * @return The JSON array string of the resolution statistics on all domain names is returned.
     */
    public String getRequestReportInfo()
    

5. Examples of SDK API operations

URl: the received access address, for example, http://www.taobao.com.

 String hostname = "www.taobao.com";
 String url = "http://www.taobao.com";

5.1 Obtain the optimal IP address based on the current network environment

String[] ip = DNSResolver.getInstance().getIpsByHost(hostname); // Obtain the optimal IP address based on the current network environment after the domain name is resolved.

5.2 Preload domain names for DNS resolution based on the current network environment

DNSResolver.getInstance().preLoadDomains(domains) // Specify the domain names that you want to pre-resolve and replace the domain names that you want to preload with the domain names that you want to use Alibaba Cloud Public DNS to resolve.

5.3 Obtain the DNS resolution results from the cache based on the current network environment

String[] ip = DNSResolver.getInstance().getIpsByHostFromCache(hostname,true);// Obtain the IP addresses from the cache based on the current network environment after the domain name is resolved.

5.4 Obtain an IPv4 address after the domain name is resolved

String IPV4 = DNSResolver.getInstance().getIPV4ByHost(hostname); // Obtain an IPv4 address after the domain name is resolved.

5.5 Obtain an IPv6 address after the domain name is resolved

String IPV6 =  DNSResolver.getInstance().getIPV6ByHost(hostname) // Obtain an IPv6 address after the domain name is resolved.

5.6 Obtain an IPv4 address from the cache after the domain name is resolved

String[] IPV4 =  DNSResolver.getInstance().getIpv4ByHostFromCache(hostname, true) // Obtain an IPv4 address from the cache after the domain name is resolved.

5.7 Obtain an IPv6 address from the cache after the domain name is resolved

String[] IPV6 =  DNSResolver.getInstance().getIpv6ByHostFromCache(hostname, true) // Obtain an IPv6 address from the cache after the domain name is resolved.

5.8 Obtain the DomainInfo object that corresponds to a specific URL

DomainInfo dinfo = DNSResolver.getInstance().getIPV4DInfoByUrl(url); // Obtain the URL in which the domain name is replaced by an IP address.

5.9 Obtain the statistics on successful queries and failed queries of Alibaba Cloud Public DNS

String reportInfo = DNSResolver.getInstance().getRequestReportInfo();// Obtain the statistics on successful queries and failed queries.

The following code shows the meanings of the fields in the JSON array string of the resolution statistics of all domain names.

 (
      {
         avgRtt = "1";                                // Average DNS resolution duration. Unit: milliseconds.
         cacheDnsNum = 0;                             // Number of cache hits.                       
         domain = "www.taobao.com"; // The domain name that you want to resolve.
         gobackLocaldnsNum = 0;                       // Number of times DNS resolution is downgraded to the local DNS server.
         localErro = 0;                               // Number of DNS resolution failures on the local DNS server.
         maxRtt = "60";                               // Maximum DNS resolution duration. Unit: milliseconds.
         noPermissionErro = 0;                        // Number of authentication failures.
         noResponseErro = 0;                          // Number of times that no response is returned.          
         requestPDnsNum = 1;                          // Number of recursive queries.
         sp = China Mobile;                                // Name of the ISP.
         successNum = 1;                              // Number of successful DNS resolutions.
         timeoutErro = 0;                             // Number of network timeout errors.
         type = 28;                                   // If the value of the type parameter is 1, IPv4 addresses are used. If the value of the type parameter is 28, IPv6 addresses are used.
         urlParameterErro = 0;                        // Number of errors that are returned because the request parameter is invalid.
         urlPathErro = 0;                             // Number of errors that are returned because the URL is invalid.
      }
         ......
 );
Important

The resolution statistics of Alibaba Cloud Public DNS are collected based on network environments, domain names, and query types.

6. Example

public class MainActivity extends AppCompatActivity {
   private Button button;
   private TextView tvInfo;
   private TextView tvResult;
   private String hostUrl = "http://www.taobao.com"; // Replace http://www.taobao.com with the URL that corresponds to the domain name that you want to resolve.
   private String hostName = "www.taobao.com"; // Replace www.taobao.com with the domain name that you want to resolve.
   private static final String TAG = "PDnsDemo";
   private static ExecutorService pool = Executors.newSingleThreadExecutor();
   private static final String PDNS_RESULT = "pdns_result";
   private static final int SHOW_CONSOLE_TEXT = 10000;
   private Handler mHandler;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.demo_activity_main);
       init();
       initHandler();
   }
 private void init() {
       tvInfo = findViewById(R.id.tv_respons_info);
       tvResult = findViewById(R.id.tv_respons);
       button = findViewById(R.id.btn_onclik);
       button.setOnClickListener(new View.OnClickListener() {
           public void onClick(View view) {
               new Thread(new Runnable() {
                      @Override
                      public void  run() {
                      // Call the getIpsByHostFromCache method in Alibaba Cloud Public DNS SDK to obtain the IP address that is resolved from the specified domain name.
                      String[] ip = DNSResolver.getInstance().getIpsByHostFromCache(hostName,true);
                      if(ip != null && ip.length >0){
                         tvInfo.setText("IP address that is resolved from the domain name: "+ ip[0]);
                      }
                      // Call the getIPV4DInfoByUrl method in Alibaba Cloud Public DNS SDK to obtain the URL in the DomainInfo object after the specified domain name is resolved. In the URL, the host field is replaced by an IP address.
                      DomainInfo dinfo = DNSResolver.getInstance().getIPV4DInfoByUrl(hostUrl);
                      if (dinfo != null) {
                           showResponse(dinfo);
                       }
                   }
               }).start();
           }
       });
   }
   private void initHandler() {
       mHandler = new Handler() {
           @Override
           public void handleMessage(Message msg) {
               switch (msg.what)  {
                   case SHOW_CONSOLE_TEXT:
                       tvResult.setText(msg.getData().getString(PDNS_RESULT) + "\n");
                       break;
               }
           }
       };
   }
   private void showResponse(final DomainInfo dinfo) {
                // Send a network request.
               String requestUrl = dinfo.url;
               HttpURLConnection conn = null;
               try {
                   URL url = new URL(requestUrl);
                   conn = (HttpURLConnection) url.openConnection();
                   // If an IP address is used for access, you must set the Host field in the HTTP request header to the domain name that is resolved.
                   conn.setRequestProperty("Host", url.getHost());// Set the Host field in the HTTP request header.
                   DataInputStream dis = new DataInputStream(conn.getInputStream());
                   int len;
                   byte[] buff = new byte[4096];
                   StringBuilder response = new StringBuilder();
                   while ((len = dis.read(buff)) != -1) {
                       response.append(new String(buff, 0, len));
                   }
                   Log.d(TAG, "Response: " + response.toString());
                   dis.close();
                   sendMessage(response.toString());
               } catch (IOException e) {
                   e.printStackTrace();
               }finally {
                   if (conn != null) {
                       conn.disconnect();
                   }
               }
           }
   private void sendMessage(String message) {
       if (mHandler != null) {
               Message msg = mHandler.obtainMessage();
               Bundle bundle = new Bundle();
               bundle.putString(PDNS_RESULT, message);
               msg.setData(bundle);
               msg.what = SHOW_CONSOLE_TEXT;
               mHandler.sendMessage(msg);
       }
   }
}

public class DnsCacheApplication extends Application {
   private String accountID = "****"; // You can replace **** with your account ID.
   private static final String TAOBAO_HOST_NAME = "www.taobao.com";// Replace www.taobao.com with the domain name that you want to preload.
   private static final String ALIYUN_HOST_NAME = "www.aliyun.com"; // Replace www.aliyun.com with the domain name that you want to preload.
   private static final int CACHE_MAX_NUMBER = 100; // Set the maximum number of DNS resolution results that can be cached. The default value is 100.
   private static final int MAX_NEGATIVE_CACHE = 30; // Set the maximum TTL period for negative caching. The default value is 30. Unit: seconds.
   private static final int MAX_TTL_CACHE = 1 * 60 * 60; // Set the maximum TTL period for caching. The default value is 3600. Unit: seconds.
 
   @Override
   public void onCreate() {
        super.onCreate();
        DNSResolver.Init(this, accountID); // Set the account ID that is used to access the SDK in the Alibaba Cloud DNS console.
        DNSResolver.setEnableShort(false); // Specify whether to enable the short mode.
        DNSResolver.setEnableIPv6(false); // Specify whether to enable IPv6 access.
        DNSResolver.setEnableCache(true); // Specify whether to enable the caching feature.
        DNSResolver.setEnableSpeedTest(false); // Specify whether to enable connection speed testing of IP addresses.
        DNSResolver.setEnableSchedulePrefetch(true); // Specify whether to enable the scheduled update of expired cache data. The default value is true, which indicates that this feature is enabled.
        DNSResolver.setIspEnable(true);// Specify whether to enable domain name caching based on ISP networks.   
        DNSResolver.setMaxTtlCache(MAX_TTL_CACHE); // Set the maximum TTL period for caching. The default value is 3600. Unit: seconds.
        DNSResolver.setMaxNegativeCache(MAX_NEGATIVE_CACHE);// Set the maximum TTL period for negative caching. The default value is 30. Unit: seconds.
        DNSResolver.setSchemaType(DNSResolver.HTTPS); // Specify whether the server access protocol is HTTP or HTTPS.
        DNSResolver.setSpeedPort(DNSResolver.PORT_80); // Set the port number for IP socket detection. The default port number is 80.
        DNSResolver.getInstance().setMaxCacheSize(CACHE_MAX_NUMBER); // Specify the maximum number of DNS resolution results that can be cached. The default value is 100.
        DNSResolver.getInstance().preLoadDomains(new String[]{TAOBAO_HOST_NAME,ALIYUN_HOST_NAME}); // Specify the domain names that you want to pre-resolve and replace the domain names that you want to preload with the domain names that you want to use Alibaba Cloud Public DNS to resolve.
   }
}

Usage notes

  1. After you use Alibaba Cloud Public DNS to resolve a domain name to an IP address, you can use the IP address to send business requests. You must specify the Host field in the HTTP request header as the domain name that has been resolved.

  2. To ensure normal service running, if you do not obtain the IP address to which a domain name is mapped by using Alibaba Cloud Public DNS SDK, you need to use the URL of the original domain name to send requests. The following section shows the sample code.

    String[] ip=DNSResolver.getInstance().getIpv4ByHostFromCache ("Domain name",true);
    if (ip.length > 0) {
    	// Replace the hostname in the URL with the IP address to send requests.
    }else {
    	// Use the URL of the original domain name to send requests.
    }
  3. A demo project helps you learn how to use Alibaba Cloud Public DNS SDK. You can download the demo project for reference.