All Products
Search
Document Center

Android SDK Development Guide

Last Updated: Apr 16, 2021

1. Preface

Alibaba Cloud public DNS SDK is developed by Alibaba Cloud to provide 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. For more information about how to use this SDK, see the demo project source code. The current version of SDK encapsulates the JSON API for DoH of Alibaba Cloud public DNS. It provides Java function interfaces for Android apps to perform DNS resolution and supports efficient domain name caching based on time to live (TTL) and least recently used (LRU) policies. Based on the features of Alibaba Cloud public DNS, the SDK also offers the following benefits:

· Easy to use:

You only need to integrate the SDK into your Android apps to use Alibaba Cloud public DNS.

· DNS resolution without delay:

The SDK implements the LRU caching algorithm so that the IP addresses obtained after DNS resolution are cached in your local server. It also actively updates the cache and deletes the data that expires based on TTL. This way, the cached data can be verified and DNS resolution is implemented without delay.

2. How to use the SDK

2.1 Integration of the jar

  1. Register your application in the console to obtain the unique ID of the application.

  2. Obtain alibaba Cloud Public DNS SDK

  3. You can use the obtained SDK pdns-sdk-android.jar in the libs directory of your project.

Notice

Currently, the console only supports the SDK in jar format. The SDK will be integrated into the console through maven later.

2.2 Application Initialization

public class DnsCacheApplication extends Application {

    private String accountID="10001"; // replace accountID with your client ID.
    private static final String TAOBAO_URL="www.taobao.com";
    private static final String M_TAOBAO_URL="m.taobao.com";
    private static final String ALIYUN_URL="aliyun.com";
    private static final int CACHE_MAX_NUMBER=100; // maximum number of cached domain names

    @Override
    public void onCreate() {
       super.onCreate();
       DNSResolver.Init(this, accountID);
       DNSResolver.setEnableShort (false);
       DNSResolver.setEnableIPv6 false);
       DNSResolver.setSchemaType(DNSResolver.HTTP);
       DNSResolver.getInstance().setMaxCacheSize(CACHE_MAX_NUMBER);      
       DNSResolver.getInstance().preLoadDomains(newString[]{TAOBAO_URL,M_TAOBAO_URL,ALIYUN_URL});
    }
}

When connecting to the Alibaba Cloud Public DNS SDK, we recommend that you integrate the SDK into your Application.

Note

DNSResolver is the core class of Alibaba Cloud Public DNS SDK. It encapsulates the DoH JSON API calls provided by Alibaba Cloud Public DNS to resolve the target domain name to the corresponding IP address.

In addition, the following access permissions must be configured when the Android project uses the SDK:

<! -- Permissions to 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"/>
   <uses-permission android:name="android.permission.WAKE_LOCK"/>
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Precautions

Android9.0 reports an exception: Didn't find class BasicHttpParams.

  • Reason: The Apache Http client is deprecated.

Because as early as Android 6.0, Google canceled its support for Apache Http clients. Starting from Android 9.0, org.apache.http.legacy will be removed from bootclasspath.

This modification has no impact on most applications whose taskVersion is earlier than 9.0 but on applications whose taskVersion is later than 9.0. If you continue to use the Apache Http interface or the referenced lib package to use this interface, can be found because the Apache Http interface cannot be found.

  • Solutions

In the AndroidManifest.xml file of the application, add the following code in <application>:

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

2.2.1 Service initialization

Alibaba Cloud Public DNS SDK uses the DNSResolve class to encapsulate Alibaba Cloud Public DNS service requests and local caches. The user passes through DNSResolve.init(this,accountID) and wait for the domain name to be initialized. ( accountID indicates the unique identifier that is automatically generated by the server when you register the accountID value in the console.

2.2.2 set pre-resolved domain names When you initialize the program, you can selectively register domain names that you may use in advance with the Alibaba Cloud Public DNS SDK for SDK resolution in advance, reducing the latency of requests during subsequent domain name resolution. Call the following method:

DNSResolve.getInstance().preLoadDomains(newString[]{TAOBAO_URL,M_TAOBAO_URL,ALIYUN_URL});
Notice

The pre-parsing interface will trigger an asynchronous network request in real time. You must use the code logic to make sure that the necessary initialization settings have been made when the pre-parsing interface is called.

2.2.3 configure whether to use the server IPV6 address

Alibaba Cloud Public DNS supports IPV4 and IPV6 dual-stack access. You can select the protocol by setting DNSResolve.setEnableIPv6(boolean enable). If the value is true, the IPV6 address is used to access the server. If the value is false, the IPV4 address is used to access the server. If this parameter is not specified, IPV4 addresses are used for access by default. In addition, when the parameter is set to IPV6, traffic is automatically switched to IPV4 if the Alibaba Cloud Public DNS cannot be accessed, and the policy supports three retries.

2.2.4 determine whether to enable the Short mode. Alibaba Cloud Public DNS supports returning data in JSON format and DoH JSON API format. You can call DNSResolve. setEnableShort (boolean enable) to enable or disable the short mode. If this parameter is not set explicitly, the short mode is disabled by default.

Use the following methods:

DNSResolve. setEnableShort (true); // The default value is false. You do not need to set this parameter. If you do not set this parameter, the default value is false.
Notice

The short mode returns a simple IP address array by using an SDK to call Alibaba Cloud Public DNS. It can reduce the amount of returned data and is suitable for scenarios that are sensitive to network traffic.

2.2.5 set the maximum number of caches for a cache module

DNSResolver.getInstance().setMaxCacheSize(CACHE_MAX_NUMBER);
private static final int CACHE_MAX_NUMBER =100;// The maximum count of cache domains is 100 by default.

You can customize the maximum value of the count parameter.

2.2.6 set the protocol for accessing the server

DNSResolver.setSchemaType(DNSResolver.HTTP); Default access mode is http.

DNSResolver.HTTP: The server interface through the HTTP protocol.

DNSResolver.HTTPS: specifies the server interface over HTTPS.

3. Service APIs

/**
  * Obtain an array of DomainInfo objects of IPv4 records corresponding to a url.
  *
  * @ param url (http://www.taobao.com example)
  * @ return an array of DomainInfo objects of the IPV4 type corresponding to the target URLs
  */
  public DomainInfo[] getIPsV4DInfoByUrl(String url) 

Note: In the Domain object, if you replace the url with the host name, the url is generated from the concatenated IP addresses. You do not need to manually replace the url.

/**
   * Obtain the DomainInfo object array of the IPv6 record corresponding to a url.
   * 
   * @ param url (http://m.taobao.com example)
   * @ return an array of IPV6 DomainInfo objects corresponding to the target url
   */
    public DomainInfo[] getIPsV6DInfoByUrl(String url) 
   

 /**
    * Obtain the DomainInfo object of the IPV4 record corresponding to a url.
    *
    * @ param url (http://m.taobao.com example)
    * @ return a single element in the DomainInfo object collection of the IPV4 type, which corresponds to the target url.
    */
    public DomainInfo getIPV4DInfoByUrl(String url) 


 /**
    * Obtain the DomainInfo object of the IPV6 record corresponding to a url.
    *
    * @ param url (http://www.taobao.com example)
    * @ return a random entry in the DomainInfo object collection of the IPV6 type in the target url.
    */
  public DomainInfo getIPV6DInfoByUrl(String url) 


/**
    * Obtain the IPV4 record array of the hostName.
    * @ param hostName as an example (www.taobao.com)
    * @ return returns the array of IPV4 addresses corresponding to the target hostName.
    */
  public String[] getIPsV4ByHost(String hostName) 


/**
    * Obtain the IPV6 record array of the hostName.
    * @ param hostName as an example (www.taobao.com)
    * @ return returns an array of IPV6 addresses corresponding to the target hostName.
    */
  public String[] getIPsV6ByHost(String hostName) 


/**
    * Obtain the IPV4 record of the hostName.
    * @ param hostName as an example (www.taobao.com)
    * @ return returns a random IPV4 address in the set of IPV4 addresses corresponding to the target hostName. 
    */
  public String getIPV4ByHost(String hostName) 


/**
    * Obtain the IPV6 address of the hostName.
    * @ param hostName as an example (www.taobao.com)
    * @ return returns a random IPV6 address in the IPV6 address set corresponding to the target hostName.
    */
 public String getIPV6ByHost(String hostName) 


/**
 * Preloading logic
 *
 * @param domains
 */
public void preLoadDomains(final String[] domains) 

  Note: The Returned domainInfo object encapsulates the following attributes:

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

   /**
    * The available url has been replaced with the ip address in the host.
    */
public String url = null


    /**
    * Set the target service name in http head.
    */
    public String host = "";


   /**
    * Returned content body
    */
   public String data = null


   /**
    * The time when the request starts.
    */
   public String startTime = null


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


  /**
   * Status values returned by the server, such as 200, 404, and 500 
   */
public String code = null

4.SDK API Usage examples

URl: enter the access address. For example, http://www.taobao.com.

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

Obtain IPv4 address:

String IPV4 = DNSResolver.getInstance().getIPV4ByHost(hostname);

Obtain the IPv6 address:

String IPV6 = DNSResolve.getInstance().getIPV6ByUrl (url);

You can obtain the DomainInfo object corresponding to a url as follows:

DomainInfo dinfo = DNSResolver.getInstance().getIPV4DInfoByUrl(url); // Obtain the url after the replacement.

Examples:

public class MainActivity extends AppCompatActivity {
   private Button button
   private TextView tvInfo
   private TextView tvResult
   private String hostUrl = "http://www.taobao.com";
   private String hostName="www.taobao.com";
   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 getIPV4ByHost() method in the Alibaba public sdk to obtain the resolved IP address of the target domain name.
               String ipv4 = DNSResolver.getInstance().getIPV4ByHost(hostName);
               tvInfo.setText("The IP address that you resolve the domain name to is:" + ipv4);
          // Call getIPV4DInfoByUr in the Alibaba public sdk to obtain the resolved domain object of the target domain name, which contains the IP after the domain name needs to be resolved. Replace the original url
              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 network request
               String requestUrl = dinfo.url
               HttpURLConnection conn = null;
               try {
                   URL url = new URL(requestUrl);
                   conn = (HttpURLConnection) url.openConnection();
                   // When an IP address is used for access, the HOST field in the HTTP request header must be set to the original domain name.
                   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 = "10001"; // replace accountID with your client ID.
   private static final String TAOBAO_URL = "www.taobao.com";
   private static final String M_TAOBAO_URL = "m.taobao.com";
   private static final String ALIYUN_URL = "aliyun.com";
   private static final String BAIDU_URL = "www.baidu.com";
   private static final int CACHE_MAX_NUMBER = 100; // maximum number of cached domain names

   @Override
   public void onCreate() {
       super.onCreate();
       DNSResolver.Init(this, accountID);
       DNSResolver.setEnableShort(false);
       DNSResolver.setEnableIPv6(false);
       DNSResolver.setSchemaType(DNSResolver.HTTP);
       DNSResolver.getInstance().setMaxCacheSize(CACHE_MAX_NUMBER);
       DNSResolver.getInstance().preLoadDomains(new String[]{TAOBAO_URL, M_TAOBAO_URL, ALIYUN_URL,BAIDU_URL});
   }
}

Precautions

  1. After Alibaba Cloud Public DNS obtains the IP address of the domain name, clients can use the IP address to send business requests. You must change the Host field in the HTTP request header to the original domain name.

  2. To help users use Alibaba Cloud Public DNS SDK faster, we provide a Demo program for you. You can

    Downloaded to a local directory for reference.

Please click here and download the Demo program.