This document describes the API operations of the Java SDK.
1. Basic configuration operations
1.1 Configure initialization
Initializes the HTTPDNS service configuration. You must complete the initialization before you can call other API operations.
Operation definition
static void init(String accountId, InitConfig config)Class
HttpDnsClient
Parameters
Parameter | Type | Required | Description |
accountId | String | Yes | The Account ID assigned by the system. Obtain it from the EMAS console. |
config | InitConfig | Yes | The initialization configuration object. |
Code example
InitConfig config = new InitConfig.Builder()
.setSecretKey("your-secret-key")
.setEnableHttps(true)
.setTimeoutMillis(2000)
.setEnableExpiredIp(true)
.build();
HttpDnsClient.init("your-account-id", config);1.2 Get a service instance
Obtains an HTTPDNS client instance for subsequent domain name resolution operations.
Interface Definition
static HttpDnsClient getClient(String accountId)
static HttpDnsClient getClient(String accountId, String secretKey)Class
HttpDnsClient
Parameters
Parameter | Type | Required | Description |
accountId | String | Yes | The Account ID assigned by the system. |
secretKey | String | No | The authentication key. |
Return Description
Type | Description |
HttpDnsClient | An HTTPDNS client instance. |
Code example
HttpDnsClient client = HttpDnsClient.getClient("your-account-id");1.3 InitConfig configuration items
You can use InitConfig.Builder to build the initialization configuration.
setSecretKey
Sets the key used to sign requests during HTTPDNS resolution.
After you set the key, the SDK signs requests that are sent to the server. This helps the HTTPDNS server authenticate resolution requests and provides tamper-proofing. This process improves the security of interactions between the SDK and the server.
Interface Definition
InitConfig.Builder setSecretKey(String secretKey)Class
InitConfig.Builder
Parameters
Parameter | Type | Required | Description |
secretKey | String | Yes | The signing key. |
setAesSecretKey
Sets the key used for encryption during HTTPDNS resolution.
After you set an encryption key, the SDK uses the AES algorithm to encrypt request parameters and responses when it sends requests to the server-side. This encryption feature provides enhanced security, but it also affects the billing logic. For more information, see Product Billing.
Interface definition
InitConfig.Builder setAesSecretKey(String aesSecretKey)Class
InitConfig.Builder
Parameters
Parameter | Type | Required | Description |
aesSecretKey | String | Yes | The encryption key. |
setEnableHttps
By default, the HTTPDNS SDK uses the HTTP protocol to send resolution requests. To use the HTTPS protocol, you can configure the SDK to use HTTPS for domain name resolution.
HTTPS requests provide greater security. However, HTTP and HTTPS requests are billed differently. For more information, see Product Billing.
You may wonder if you still need encryption if you use HTTPS. Yes, you do. The two work at different layers. The HTTPS protocol ensures transport layer security. However, you can still view parameters and response details if you capture packets. AES encryption ensures security at the HTTPDNS service layer. Even if you capture packets, you cannot see the plaintext content. Therefore, you can enable both as needed.
Interface Definition
InitConfig.Builder setEnableHttps(boolean enableHttps)Class
InitConfig.Builder
Parameters
Parameter | Type | Required | Description |
enableHttps | boolean | Yes | Specifies whether to use the HTTPS protocol for domain name resolution. `true`: Enables HTTPS resolution. `false`: Disables HTTPS resolution. |
setTimeoutMillis
Sets the timeout period for domain name resolution. The default value is 2000 ms.
Interface Definition
InitConfig.Builder setTimeoutMillis(int timeoutMillis)Class
InitConfig.Builder
Parameters
Parameter | Type | Required | Description |
timeoutMillis | int | Yes | The timeout period for domain name resolution, in milliseconds. The default value is 2000 ms. The maximum value is 5000 ms. |
setEnableExpiredIp
The SDK follows the DNS protocol and caches domain name resolution results according to their Time to Live (TTL). This improves the efficiency of retrieving IP addresses when the application initiates network requests. When the cache expires, if the application calls a resolution operation to retrieve an IP address, different situations occur:
If the application calls a synchronous non-blocking operation and the cache has expired, the SDK cannot immediately retrieve a new resolution result from the server. To avoid blocking the thread, the operation returns an empty result. The caller must handle the fallback to LocalDNS resolution.
If the application calls a synchronous or asynchronous operation, the SDK sends a resolution request to retrieve a new result from the server. This process takes some time. The synchronous operation blocks the thread until a new result is obtained. The asynchronous operation provides a callback only after a new result is obtained.
The SDK provides an option to reuse expired IP addresses. If you set this option to true, the operations can immediately return the expired IP address even if the cached IP has expired. This reduces the processing time for the DNS step and improves network request performance. At the same time, when the SDK finds that the IP has expired, it also starts an asynchronous thread to resolve the domain name and retrieve a new resolution result.
Therefore, the side effects of enabling this option are minimal, especially when the resolution configuration of the domain name itself does not change frequently, such as for primary site domain names or static gateway domain names. If the domain name resolution does change, enabling this option affects only the first request after the domain's cache expires. This is because when the SDK is called and finds an expired IP, it always immediately initiates an update to the domain name resolution.
Enabled by default.
When set to true, the SDK returns the expired IP address in real time and still performs an asynchronous update to retrieve the latest IP information.
Interface Definition
InitConfig.Builder setEnableExpiredIp(boolean enableExpiredIp)Class
InitConfig.Builder
Parameters
Parameter | Type | Required | Description |
enableExpiredIp | boolean | Yes | Specifies whether to allow the return of IP addresses that have exceeded their TTL. `true`: Allows returning expired IP addresses. `false`: Does not return expired IP addresses. |
enableMemoryCache
Sets whether to enable the memory cache.
Interface Definition
InitConfig.Builder enableMemoryCache(boolean enable)Class
InitConfig.Builder
Parameters
Parameter | Type | Required | Description |
enable | boolean | Yes | `true`: Enables the memory cache (default). `false`: Disables the memory cache. |
setRegion
If your application needs to use HTTPDNS in an environment outside China, you can set the startup service node for this SDK to improve resolution efficiency. After you set the node, the SDK uses that node for domain name resolution and for subsequent updates to the scheduling node list.
Interface Definition
InitConfig.Builder setRegion(Region region)Class
InitConfig.Builder
Parameters
Parameter | Type | Required | Description |
region | Region | Yes | The enumeration value for the service node region, used for selecting a service region outside China. If not specified, the service node in the Chinese mainland is used. |
setIPRankingList
Sets the IP preference list. After you configure this operation, if the corresponding domain name is resolved, the SDK performs IP speed tests on the returned IP addresses. It dynamically sorts the returned list to ensure that the first IP address has better availability.
Only the preference sorting of IPv4 addresses is supported.
Interface Definition
InitConfig.Builder setIPRankingList(List<? extends IPRankingBean> ipRankingList)Class
InitConfig.Builder
Parameters
Parameter | Type | Required | Description |
ipRankingList | List<IPRankingBean> | Yes | The IP preference configuration list. |
configCacheTtlChanger
By default, each resolution result uses the TTL provided by the server to determine if it has expired. To modify the TTL of a resolution result, you can configure it using this operation.
Interface Definition
InitConfig.Builder configCacheTtlChanger(CacheTtlChanger changer)Class
InitConfig.Builder
Parameters
Parameter | Type | Required | Description |
changer | CacheTtlChanger | Yes | Implementing a custom TTL interface |
setNotUseHttpDnsFilter
To prevent specific domain names from being resolved using HTTPDNS, you can filter out those domain names with this operation. Filtered domain names return an empty resolution result. You need to fall back to LocalDNS for domain name resolution.
Interface Definition
InitConfig.Builder setNotUseHttpDnsFilter(NotUseHttpDnsFilter filter)Class
InitConfig.Builder
Parameters
Parameter | Type | Required | Description |
filter | NotUseHttpDnsFilter | Yes | Configure the blacklist policy. |
setSdnsGlobalParams
Sets global parameters for custom resolution (SDNS). These global parameters do not affect the extra parameter settings of the custom resolution operation. They are merged with the extra parameters of the custom resolution operation. Each custom resolution request carries these global parameters.
Interface Definition
InitConfig.Builder setSdnsGlobalParams(Map<String, String> params)Class
InitConfig.Builder
Parameters
Parameter | Type | Required | Description |
params | Map<String, String> | Yes | Global parameters for custom resolution. |
2. Domain name resolution operations
2.1 Set domain names for pre-resolution
After the application starts and the SDK initialization is complete, you can immediately call this operation. You can set the hot spot domain names that you may use later. This allows the SDK to resolve them in advance and reduces the latency of subsequent resolution requests.
If you call this operation while the application is running, the SDK also immediately resolves the domain names in the specified list. This refreshes the resolution results for these domain names and records them in the cache. This is equivalent to forcing an update. This is typically used after certain business actions to refresh the current domain name resolution and force a new domain name scheduling.
To balance resolution efficiency and response speed, the SDK limits each batch resolution task submitted to the server to five domain names. Therefore, if the pre-resolution list contains more than five domain names, the SDK automatically submits them for resolution in batches.
setPreResolveHosts
Interface Definition
void setPreResolveHosts(List<String> hostList)
void setPreResolveHosts(List<String> hostList, RequestIpType requestIpType)Class
HttpDnsClient
Parameters
Parameter | Type | Required | Description |
hostList | List<String> | Yes | A list of domain names for pre-resolution. The domain names to be resolved must be pure domain name strings. They cannot contain protocol headers (such as http://), paths, or ports. Otherwise, resolution exceptions may occur. Wildcard domain names are not supported. |
requestIpType | RequestIpType | No | The IP type for pre-resolution. If this parameter is not specified, the default value is `RequestIpType.v4`. |
Code example
List<String> hosts = Arrays.asList("www.example.com", "api.example.com");
client.setPreResolveHosts(hosts, RequestIpType.both);2.2 Synchronous non-blocking resolution
Using a synchronous non-blocking operation to resolve a domain name does not block the current thread, but it may return an empty result.
This operation queries only the cache and returns the resolution result from the cache. If no resolution result is in the cache or the result has expired, the domain name resolution is performed in a worker thread. After a successful resolution, the cache is updated for the next domain name resolution call.
getHttpDnsResultForHostSyncNonBlocking
Interface definition
HTTPDNSResult getHttpDnsResultForHostSyncNonBlocking(String host, RequestIpType type)
HTTPDNSResult getHttpDnsResultForHostSyncNonBlocking(String host, RequestIpType type, String clientIp)
HTTPDNSResult getHttpDnsResultForHostSyncNonBlocking(String host, RequestIpType type, Map<String, String> params, String cacheKey)
HTTPDNSResult getHttpDnsResultForHostSyncNonBlocking(String host, RequestIpType type, Map<String, String> params, String cacheKey, String clientIp)Class
HttpDnsClient
Parameters
Parameter | Type | Required | Description |
host | String | Yes | The domain name to resolve. |
type | RequestIpType | Yes | The IP type to resolve. We recommend that you use `RequestIpType.both`. |
clientIp | String | No | The client IP address. This is used in server-side scenarios to specify the actual client IP address for more accurate resolution results. |
params | Map<String, String> | No | Extra parameters carried with the domain name resolution, corresponding to the `event.parameters` parameter in the server-side custom resolution function. |
cacheKey | String | No | The local cache key for the domain name. When using SDNS, you must pass a non-null value. If changes to extra parameters require re-resolution from the server, you need to change the `cacheKey`. |
Return value
Type | Description |
HTTPDNSResult | The resolution result. |
Code example
HTTPDNSResult result = client.getHttpDnsResultForHostSyncNonBlocking(
"www.example.com",
RequestIpType.both
);
if (result != null && result.getIps() != null && result.getIps().length > 0) {
String ip = result.getIps()[0];
}2.3 Synchronous resolution
Using a synchronous resolution operation to resolve a domain name blocks the current thread until a valid resolution result is obtained and returned.
This operation first queries the cache. If a usable resolution result exists in the cache, it is returned immediately. If no usable result is in the cache, the thread that called the resolution is blocked. The domain name resolution is performed in a worker thread. The resolution result is returned after the resolution is complete, or an empty value is returned if the timeout period is reached.
The total time for a synchronous resolution operation is controlled by the timeout configuration. If the resolution is not successful within the timeout period, an empty resolution result is returned immediately.
getHttpDnsResultForHostSync
Interface Definition
HTTPDNSResult getHttpDnsResultForHostSync(String host, RequestIpType type)
HTTPDNSResult getHttpDnsResultForHostSync(String host, RequestIpType type, String clientIp)
HTTPDNSResult getHttpDnsResultForHostSync(String host, RequestIpType type, Map<String, String> params, String cacheKey)
HTTPDNSResult getHttpDnsResultForHostSync(String host, RequestIpType type, Map<String, String> params, String cacheKey, String clientIp)Class
HttpDnsClient
Parameters
Parameter | Type | Required | Description |
host | String | Yes | The domain name to resolve. |
type | RequestIpType | Yes | The IP type to resolve. We recommend that you use `RequestIpType.both`. |
clientIp | String | No | The client IP address. This is used in server-side scenarios to specify the actual client IP address. |
params | Map<String, String> | No | Extra parameters carried with the domain name resolution, corresponding to the `event.parameters` parameter in the server-side custom resolution function. |
cacheKey | String | No | The local cache key for the domain name. When using SDNS, you must pass a non-null value. If changes to extra parameters require re-resolution from the server, you need to change the `cacheKey`. |
Return value
Type | Description |
HTTPDNSResult | The resolution result. |
Code example
HTTPDNSResult result = client.getHttpDnsResultForHostSync(
"www.aliyun.com",
RequestIpType.both
);2.4 Asynchronous resolution
Using an asynchronous resolution operation to resolve a domain name does not block the current thread. The resolution result is returned through a callback.
This operation first queries the cache. If a usable resolution result exists in the cache, it is immediately returned through a callback. If no usable result is in the cache, the domain name resolution is performed in a worker thread. The resolution result is returned through the callback after the resolution is complete or the timeout period is reached.
The total time for an asynchronous resolution operation is controlled by the timeout configuration. If the resolution is not successful within the timeout period, an empty resolution result is returned immediately through the callback.
getHttpDnsResultForHostAsync
Interface Definition
void getHttpDnsResultForHostAsync(String host, RequestIpType type, HttpDnsCallback callback)
void getHttpDnsResultForHostAsync(String host, RequestIpType type, String clientIp, HttpDnsCallback callback)
void getHttpDnsResultForHostAsync(String host, RequestIpType type, Map<String, String> params, String cacheKey, HttpDnsCallback callback)
void getHttpDnsResultForHostAsync(String host, RequestIpType type, Map<String, String> params, String cacheKey, String clientIp, HttpDnsCallback callback)Class
HttpDnsClient
Parameters
Parameter | Type | Required | Description |
host | String | Yes | The domain name to resolve. |
type | RequestIpType | Yes | The IP type to resolve. We recommend that you use `RequestIpType.both`. |
callback | HttpDnsCallback | Yes | The callback operation for the domain name resolution result. |
clientIp | String | No | The client IP address, for server-side scenarios. |
params | Map<String, String> | No | Extra parameters carried with the domain name resolution, corresponding to the `event.parameters` parameter in the server-side custom resolution function. |
cacheKey | String | No | The local cache key for the domain name. When using SDNS, you must pass a non-null value. If changes to extra parameters require re-resolution from the server, you need to change the `cacheKey`. |
Code example
client.getHttpDnsResultForHostAsync("www.example.com", RequestIpType.both,
new HttpDnsCallback() {
@Override
public void onHttpDnsCompleted(HTTPDNSResult result) {
if (result != null && result.getIps() != null) {
String[] ips = result.getIps();
// Use the resolution result.
}
}
});3. Cache management operations
3.1 Clear the cache for a specific domain name
Users of Alibaba Cloud DNS can call this operation to clear the local cache. This allows domain name configuration changes to take effect in seconds.
For example, assume the domain name is xxx.com and its resolved IP address is ip1. When ip1 is under attack, you need to migrate traffic to ip2. The flow is as follows:
First, in the Cloud DNS console, change the IP address for the domain name to ip2. The HTTPDNS server immediately retrieves this change information and purges the ip1 cache for that domain name on the server-side.
Manually call this operation to clear the local cache for the xxx.com domain name.
The next request after the application clears the cache causes the server-side to re-request the authoritative server to retrieve the latest resolved IP address, ip2. This makes the frontend resolution result immediately take effect as ip2.
cleanHostCache
Interface Definition
void cleanHostCache(ArrayList<String> hosts)Class
HttpDnsClient
Parameters
Parameter | Type | Required | Description |
hosts | ArrayList<String> | Yes | An array of host domain names to clear. To clear all data, pass `null` or an empty array. |
Code example
// Clear the cache for a specific domain name.
ArrayList<String> hosts = new ArrayList<>();
hosts.add("www.example.com");
client.cleanHostCache(hosts);
// Clear all caches.
client.cleanHostCache(null);4. Troubleshooting and tracking operations
4.1 Get the SessionId
Retrieves the sessionId used to track the resolution process. If you encounter a resolution exception, provide this information when you seek technical support through DingTalk, tickets, or other channels.
The sessionId is randomly generated, is 12 characters long, and remains unchanged throughout the application lifecycle.
getSessionId
Interface Definition
String getSessionId()Class
HttpDnsClient
Return value
Type | Description |
String | sessionId |
Code example
String sessionId = client.getSessionId();
System.out.println("SessionId: " + sessionId);4.2 Get the SDK version number
Retrieves the current SDK version number.
getSdkVersion
Interface Definition
String getSdkVersion()Class
HttpDnsClient
Return value
Type | Description |
String | The SDK version number. |
Code example
String version = client.getSdkVersion();
System.out.println("SDK Version: " + version);4.3 Log control
HttpDnsLog.enable
Sets whether to enable logging for HTTPDNS. It is disabled by default.
Interface Definition
static void enable(boolean enable)Class
HttpDnsLog
Parameters
Parameter | Type | Required | Description |
enable | boolean | Yes | Whether to print logs. |
Code example
HttpDnsLog.enable(true);HttpDnsLog.setLogger
You can retrieve the logs that are output by the SDK by setting a log callback class.
Interface Definition
static void setLogger(ILogger logger)Class
HttpDnsLog
Parameters
Parameter | Type | Required | Description |
logger | ILogger | Yes | After you configure this operation, the internal logs of the SDK are returned through the ILogger interface callback. This lets you control the printing and storage of logs. |
Code example
HttpDnsLog.setLogger(new ILogger() {
@Override
public void log(String msg) {
System.out.println("[HTTPDNS] " + msg);
}
});HttpDnsLog.removeLogger
Deletes the log callback class.
Interface Definition
static void removeLogger(ILogger logger)Class
HttpDnsLog
Parameters
Parameter | Type | Required | Description |
logger | ILogger | Yes | The logger that was previously added. |
Code example
HttpDnsLog.removeLogger(myLogger);5. Other operations
5.1 Set the region
Dynamically updates the region node.
setRegion
Interface Definition
void setRegion(Region region)Class
HttpDnsClient
Parameters
Parameter | Type | Required | Description |
region | Region | Yes | The region node. Set a region outside China for service area selection. |
Code example
client.setRegion(Region.HK); // Switch to the China (Hong Kong) node.5.2 Correct signature time
After you perform this operation, if a time drift occurs, the device time is corrected with each network request. If you do not perform this operation, the device time is used.
setAuthCurrentTime
Interface Definition
void setAuthCurrentTime(long time)Class
HttpDnsClient
Parameters
Parameter | Type | Required | Description |
time | long | Yes | The current UNIX timestamp in milliseconds. |
Code example
HttpDnsClient client = HttpDnsClient.getClient(accountId);
client.setAuthCurrentTime(System.currentTimeMillis());6. Common data structures
6.1 HTTPDNSResult
The data class for the resolution result returned by a domain name resolution operation.
getHost
Retrieves the corresponding domain name.
Interface Definition
String getHost()Return value
Type | Description |
String | The domain name. |
getIps
Retrieves the resolved IPv4 addresses.
Interface Definition
String[] getIps()Return value
Type | Description |
String[] | The resolved IPv4 addresses for the domain name. |
getIpv6s
Retrieves the resolved IPv6 addresses.
Interface Definition
String[] getIpv6s()Return value
Type | Description |
String[] | The resolved IPv6 addresses for the domain name. |
getExtras
Retrieves extra parameters from the resolution. Only custom resolutions have this data.
Interface Definition
String getExtras()Return value
Type | Description |
String | The extra parameter string. |
isExpired
Indicates whether the resolution result has expired. Expiration is calculated based on the time the result was obtained and the TTL configured for the domain name.
Interface Definition
boolean isExpired()Return value
Type | Description |
boolean | `true`: Expired. `false`: Not expired. |
getTtl
Retrieves the Time to Live (TTL) of the resolution result.
Interface Definition
int getTtl()Return value
Type | Description |
int | The TTL, in seconds. |
6.2 RequestIpType
The enumeration for the requested IP type.
Enumeration value | Description |
| The type to resolve is IPv4. |
| The type to resolve is IPv6. |
| The types to resolve are IPv4 and IPv6. |
Code example
// Resolve both IPv4 and IPv6.
HTTPDNSResult result = client.getHttpDnsResultForHostSyncNonBlocking(
"www.example.com",
RequestIpType.both
);6.3 Region
The enumeration for the service node region, used for selecting a service region outside China.
Enumeration value | Description |
| The Chinese mainland (default) |
| China (Hong Kong) |
| Singapore |
| Germany |
| United States |
Code example
new InitConfig.Builder().setRegion(Region.SG); // Singapore node6.4 HttpDnsCallback
The callback interface for the asynchronous domain name resolution operation.
onHttpDnsCompleted
The callback function after the resolution is complete. This function is called for both success and failure.
Interface Definition
void onHttpDnsCompleted(HTTPDNSResult result)Parameters
Parameter | Type | Description |
result | HTTPDNSResult | The resolution result object. |
Code example
client.getHttpDnsResultForHostAsync("www.example.com", RequestIpType.both,
new HttpDnsCallback() {
@Override
public void onHttpDnsCompleted(HTTPDNSResult result) {
if (result != null && result.getIps() != null) {
// Resolution succeeded.
} else {
// Resolution failed or no result.
}
}
});6.5 ILogger
The log interface.
log
The log method.
Interface Definition
void log(String msg)Parameters
Parameter | Type | Description |
msg | String | The log. |
Code example
HttpDnsLog.setLogger(new ILogger() {
@Override
public void log(String msg) {
// Custom log processing.
System.out.println("[HTTPDNS] " + msg);
}
});6.6 CacheTtlChanger
The interface for customizing the TTL of a domain name resolution result.
changeCacheTtl
Customizes the TTL.
Interface Definition
int changeCacheTtl(String host, RequestIpType type, int ttl)Parameters
Parameter | Type | Description |
host | String | The domain name. |
type | RequestIpType | The IP type. |
ttl | int | The original TTL. |
Response Description
Type | Description |
int | The customized TTL. If no customization is needed, return the original TTL. |
Code example
new InitConfig.Builder()
.configCacheTtlChanger(new CacheTtlChanger() {
@Override
public int changeCacheTtl(String host, RequestIpType type, int ttl) {
if ("www.aliyun.com".equals(host)) {
return ttl * 10;
}
return ttl;
}
});6.7 NotUseHttpDnsFilter
The interface for filtering domain names that should not be resolved by HTTPDNS.
notUseHttpDns
Configures domain names that should not be resolved by HTTPDNS.
Interface Definition
boolean notUseHttpDns(String hostName)Parameters
Parameter | Type | Description |
hostName | String | The domain name. |
Return value
Type | Description |
boolean | `true`: Filters the current domain name. The current domain name is not resolved by HTTPDNS in the cloud. `false`: Does not filter the current domain name. The current domain name is resolved by HTTPDNS in the cloud. |
Code example
new InitConfig.Builder()
.setNotUseHttpDnsFilter(new NotUseHttpDnsFilter() {
@Override
public boolean notUseHttpDns(String hostName) {
return "www.aliyun.com".equals(hostName);
}
});6.8 IPRankingBean
The IP preference configuration item. After you configure this operation, if the corresponding domain name is resolved, the SDK performs IP speed tests on the returned IP addresses. It dynamically sorts the returned list to ensure that the first IP address has better availability.
Constructor
IPRankingBean(String hostName, int port)Parameters
Parameter | Type | Description |
hostName | String | The domain name for IP preference sorting. |
port | int | The port used to test the speed. |
getHostName
Retrieves the domain name.
Interface Definition
String getHostName()getPort
Retrieves the port.
Interface Definition
int getPort()Code example
List<IPRankingBean> list = new ArrayList<>();
list.add(new IPRankingBean("www.example.com", 443));
list.add(new IPRankingBean("api.example.com", 8080));
new InitConfig.Builder()
.setIPRankingList(list);