Integrate HTTPDNS into your Flutter app using the pure Dart SDK. For integration principles, see Client Integration Overview.
Flutter is an open-source framework from Google for building natively compiled multi-platform apps from a single codebase.
The HTTPDNS SDK is a pure Dart implementation with no native platform dependencies. It integrates with common Flutter networking frameworks (Dio, HttpClient, http package). Source code is available on GitHub and pub.dev.
The following sections cover installation, configuration, best practices, and API reference:
1. Getting started
1.1. Activate the service
To activate HTTPDNS, see Quick Start.
1.2. Obtain configurations
Obtain your AccountId, SecretKey, and AESSecretKey from Development configurations in the EMAS console. You need these values to initialize the SDK.
2. Installation and configuration
2.1. Add the Flutter dependency
In your Flutter project's pubspec.yaml file, add the following dependencies:
dependencies:
flutter:
sdk: flutter
aliyun_httpdns: ^2.0.0 # Get the latest version number from the SDK release notes
dio: ^5.9.0 # Dio networking library
http: ^1.2.0 # http package
After adding the dependencies, run flutter pub get.
From version 2.0.0, the SDK is a pure Dart implementation with no native Android or iOS dependencies.
3. Configuration and usage
3.1. Initialization configuration
Initialize the SDK at app startup with your AccountId, SecretKey, and feature flags:
// Initialize HTTPDNS
final config = AliyunHttpdnsConfig(
accountId: Your AccountId,
secretKey: 'Your SecretKey',
httpsEnabled: true,
persistentCacheEnabled: true,
reuseExpiredIPEnabled: true,
preResolveAfterNetworkChanged: true,
ipRankingDatasource: {
'www.aliyun.com': 443,
},
);
await AliyunHttpdns.init(config);
// Enable logging (optional)
AliyunHttpdns.setLogEnabled(true);
// Set pre-resolve hosts
await AliyunHttpdns.setPreResolveHosts(['www.aliyun.com'], ipType: HttpdnsIpType.auto);
3.1.1. Log configuration
Enable log output during development:
AliyunHttpdns.setLogEnabled(true);
// Custom log handler (optional)
AliyunHttpdns.setLogHandler((message) {
print(message);
});
3.1.2. SessionId recording
Retrieve the sessionId to identify a single app run in resolution logs for troubleshooting:
final sessionId = AliyunHttpdns.getSessionId();
print("SessionId = $sessionId");
3.2. Domain name resolution
3.2.1. Pre-resolution
Pre-resolve domain names to cache results before they are needed:
await AliyunHttpdns.setPreResolveHosts(["www.aliyun.com", "www.example.com"], ipType: HttpdnsIpType.auto);
The SDK resolves and caches results in memory. Subsequent requests use the cached result directly.
3.2.2. Domain name resolution
Resolve a domain name to retrieve IP addresses:
Future<void> _resolve() async {
final result = await AliyunHttpdns.resolveHostSyncNonBlocking('www.aliyun.com', ipType: HttpdnsIpType.auto);
final ipv4List = result?.ips ?? [];
final ipv6List = result?.ipv6s ?? [];
print('IPv4: $ipv4List');
print('IPv6: $ipv6List');
}
4. Flutter best practices
4.1. How it works
This approach integrates HTTPDNS at the HTTP client level using a custom adapter:
-
Create a custom HTTP client adapter to intercept network requests.
-
In the adapter, call the HTTPDNS plugin to resolve domain names to IP addresses.
-
Use the resolved IP addresses to create direct socket connections.
-
For HTTPS connections, ensure that Server Name Indication (SNI) is correctly set to the original domain name.
This integrates HTTPDNS directly at the HTTP client level for simple, efficient resolution.
4.2. Example
A complete Flutter application demonstrating HTTPDNS integration.
4.2.1. Custom HTTP client adapter implementation
The custom adapter in lib/net/httpdns_http_client_adapter.dart intercepts HTTP requests, resolves domain names via HTTPDNS, and creates socket connections with the resolved IP. This solution was designed by the EMAS team — please provide attribution if you reference it.
Supports Dio, HttpClient, and the http package:
import 'dart:io';
import 'package:dio/io.dart';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart';
import 'package:flutter/foundation.dart';
import 'package:aliyun_httpdns/aliyun_httpdns.dart';
// Dio adapter
IOHttpClientAdapter buildHttpdnsHttpClientAdapter() {
final HttpClient client = HttpClient();
_configureHttpClient(client);
_configureConnectionFactory(client);
final IOHttpClientAdapter adapter = IOHttpClientAdapter(createHttpClient: () => client)
..validateCertificate = (cert, host, port) => true;
return adapter;
}
// Native HttpClient
HttpClient buildHttpdnsNativeHttpClient() {
final HttpClient client = HttpClient();
_configureHttpClient(client);
_configureConnectionFactory(client);
return client;
}
// http package adapter
http.Client buildHttpdnsHttpPackageClient() {
final HttpClient httpClient = buildHttpdnsNativeHttpClient();
return IOClient(httpClient);
}
// HttpClient basic configuration
void _configureHttpClient(HttpClient client) {
client.findProxy = (Uri _) => 'DIRECT';
client.idleTimeout = const Duration(seconds: 30);
client.maxConnectionsPerHost = 8;
}
// Configure a connection factory based on HTTPDNS
// This solution was designed and implemented by the EMAS team. Provide attribution if you reference it.
void _configureConnectionFactory(HttpClient client) {
client.connectionFactory = (Uri uri, String? proxyHost, int? proxyPort) async {
final String domain = uri.host;
final bool https = uri.scheme.toLowerCase() == 'https';
final int port = uri.port == 0 ? (https ? 443 : 80) : uri.port;
final List<InternetAddress> targets = await _resolveTargets(domain);
final Object target = targets.isNotEmpty ? targets.first : domain;
if (!https) {
return Socket.startConnect(target, port);
}
// HTTPS: First TCP, then TLS (SNI=domain name), and keep it cancellable
bool cancelled = false;
final Future<ConnectionTask<Socket>> rawStart = Socket.startConnect(target, port);
final Future<Socket> upgraded = rawStart.then((task) async {
final Socket raw = await task.socket;
if (cancelled) {
raw.destroy();
throw const SocketException('Connection cancelled');
}
final SecureSocket secure = await SecureSocket.secure(
raw,
host: domain, // Important: Use the original domain name as the SNI
);
if (cancelled) {
secure.destroy();
throw const SocketException('Connection cancelled');
}
return secure;
});
return ConnectionTask.fromSocket(
upgraded,
() {
cancelled = true;
try {
rawStart.then((t) => t.cancel());
} catch (_) {}
},
);
};
}
// Resolve the target IP list through HTTPDNS
Future<List<InternetAddress>> _resolveTargets(String domain) async {
try {
final result = await AliyunHttpdns.resolveHostSyncNonBlocking(domain, ipType: HttpdnsIpType.auto);
final List<String> ipv4 = result?.ips ?? [];
final List<String> ipv6 = result?.ipv6s ?? [];
final List<InternetAddress> targets = [
...ipv4.map(InternetAddress.tryParse).whereType<InternetAddress>(),
...ipv6.map(InternetAddress.tryParse).whereType<InternetAddress>(),
];
if (targets.isEmpty) {
debugPrint('[dio] HTTPDNS no result for $domain, fallback to system DNS');
} else {
debugPrint('[dio] HTTPDNS resolved $domain -> ${targets.first.address}');
}
return targets;
} catch (e) {
debugPrint('[dio] HTTPDNS resolve failed: $e, fallback to system DNS');
return const <InternetAddress>[];
}
}
4.2.2. Adapter integration and usage
In lib/main.dart, initialize HTTPDNS and configure the networking library to use the custom adapter:
class _MyHomePageState extends State<MyHomePage> {
late final Dio _dio;
late final HttpClient _httpClient;
late final http.Client _httpPackageClient;
@override
void initState() {
super.initState();
// Initialize HTTPDNS
_initHttpDnsOnce();
// Configure the networking library to use the HTTPDNS adapter
_dio = Dio();
_dio.httpClientAdapter = buildHttpdnsHttpClientAdapter();
_dio.options.headers['Connection'] = 'keep-alive';
_httpClient = buildHttpdnsNativeHttpClient();
_httpPackageClient = buildHttpdnsHttpPackageClient();
}
Future<void> _initHttpDnsOnce() async {
try {
final config = AliyunHttpdnsConfig(
accountId: Your AccountId,
secretKey: 'Your SecretKey',
httpsEnabled: true,
reuseExpiredIPEnabled: true,
);
await AliyunHttpdns.init(config);
AliyunHttpdns.setLogEnabled(true);
// Set pre-resolve hosts
await AliyunHttpdns.setPreResolveHosts(['www.aliyun.com'], ipType: HttpdnsIpType.auto);
} catch (e) {
debugPrint('[httpdns] init failed: $e');
}
}
}
Requests automatically use HTTPDNS for domain name resolution:
// Use Dio
final response = await _dio.get('https://www.aliyun.com');
// Use HttpClient
final request = await _httpClient.getUrl(Uri.parse('https://www.aliyun.com'));
final response = await request.close();
// Use the http package
final response = await _httpPackageClient.get(Uri.parse('https://www.aliyun.com'));
4.2.3. Clean up resources
Clean up resources when the component is destroyed:
@override
void dispose() {
_urlController.dispose();
_httpClient.close();
_httpPackageClient.close();
super.dispose();
}
5. API
5.1. Log output control
Controls whether logs are printed.
AliyunHttpdns.setLogEnabled(true);
5.2. Initialization
Initialize the SDK configuration at app startup:
// Create a configuration
final config = AliyunHttpdnsConfig(
accountId: Your AccountId, // Required
secretKey: 'your_secret_key', // Optional
aesSecretKey: 'your_aes_secret_key', // Optional
region: HttpdnsRegion.cn, // Default: Chinese mainland
httpsEnabled: true, // Default: true
persistentCacheEnabled: true, // Persistent cache
reuseExpiredIPEnabled: true, // Reuse expired IP
preResolveAfterNetworkChanged: true, // Pre-resolve after network change
ipRankingDatasource: { // IP ranking configuration (optional)
'www.aliyun.com': 443,
},
timeout: 2, // Request timeout (seconds)
);
// Initialize the SDK
await AliyunHttpdns.init(config);
// Enable logging (optional)
AliyunHttpdns.setLogEnabled(true);
Initialization parameters:
|
Parameter Name |
Type |
Required |
Features |
|
accountId |
int |
Required parameter |
Account ID |
|
secretKey |
String? |
Optional parameters |
The key to add a signature. |
|
aesSecretKey |
String? |
Optional parameters |
The key to encrypt data. |
|
region |
HttpdnsRegion |
Optional Parameters |
The area where the endpoint is deployed. Default: cn. |
|
httpsEnabled |
bool |
Optional parameters |
Specifies whether to use the HTTPS resolution link. Default: true. |
|
persistentCacheEnabled |
bool |
Optional parameters |
Specifies whether to enable the persistent cache. Default: false. |
|
reuseExpiredIPEnabled |
bool |
Optional parameters |
Specifies whether to allow the reuse of expired IP addresses. Default: false. |
|
preResolveAfterNetworkChanged |
bool |
Optional parameters |
Specifies whether to automatically refresh resolutions when the network changes. Default: false. |
|
discardExpiredAfterSeconds |
int? |
Optional parameters |
The expiration time for discarding cached data, in seconds. |
|
ipRankingDatasource |
Map<String, int>? |
Optional parameters |
IP ranking configuration. A map of domain names and ports. |
|
timeout |
int |
Optional parameters |
The request timeout duration in seconds. Default: 2. |
5.3. Domain name resolution
Resolves a domain name. The SDK provides three resolution methods:
5.3.1 Synchronous non-blocking resolution (recommended)
Returns the cached result immediately. If no cache hit, returns null and resolves in the background.
final result = await AliyunHttpdns.resolveHostSyncNonBlocking(
'www.aliyun.com',
ipType: HttpdnsIpType.auto,
);
// With SDNS parameters
final result2 = await AliyunHttpdns.resolveHostSyncNonBlocking(
'www.aliyun.com',
ipType: HttpdnsIpType.auto,
sdnsParams: {'key': 'value'},
cacheKey: 'custom_cache_key',
);
5.3.2 Synchronous blocking resolution
Blocks until a result is returned or the request times out.
final result = await AliyunHttpdns.resolveHostSync(
'www.aliyun.com',
ipType: HttpdnsIpType.auto,
);
// With SDNS parameters
final result2 = await AliyunHttpdns.resolveHostSync(
'www.aliyun.com',
ipType: HttpdnsIpType.auto,
sdnsParams: {'key': 'value'},
cacheKey: 'custom_cache_key',
);
5.3.3 Asynchronous callback resolution
Returns the result through a callback function.
await AliyunHttpdns.resolveHostAsync(
'www.aliyun.com',
ipType: HttpdnsIpType.auto,
callback: (result) {
print('Resolution result: $result');
},
);
// With SDNS parameters
await AliyunHttpdns.resolveHostAsync(
'www.aliyun.com',
ipType: HttpdnsIpType.auto,
sdnsParams: {'key': 'value'},
cacheKey: 'custom_cache_key',
callback: (result) {
print('Resolution result: $result');
},
);
Parameter description
|
Parameter name |
Type |
Required |
Feature |
|
host |
String |
Required parameters |
The domain name to resolve. |
|
ipType |
HttpdnsIpType |
Optional parameters |
Requested IP type: auto, v4, v6, or both. |
|
sdnsParams |
Map<String, String>? |
Optional parameters |
SDNS parameters for custom resolution. |
|
cacheKey |
String? |
This parameter is optional. |
A custom cache key. |
Returned data structure (ResolveResult)
|
Field Name |
Type |
Feature |
|
host |
String |
The domain name. |
|
ips |
List |
A list of IPv4 addresses. |
|
ipv6s |
List |
A list of IPv6 addresses. |
|
ttl |
int |
The IPv4 TTL in seconds. |
|
v6ttl |
int |
The IPv6 TTL in seconds. |
5.4. Pre-resolve domain names
Pre-resolves domain names and caches results in the SDK. Subsequent resolution requests retrieve results directly from the cache.
await AliyunHttpdns.setPreResolveHosts(
["www.aliyun.com"],
ipType: HttpdnsIpType.auto
);
Parameters:
|
Parameter name |
Type |
Required |
Features |
|
hosts |
List |
Required parameters |
A list of domain names to pre-resolve. |
|
ipType |
HttpdnsIpType |
Optional parameters |
Requested IP type: auto, v4, v6, or both. |
5.5. Get SessionId
Retrieves the SessionId, which is used for troubleshooting and tracking issues.
final sessionId = await AliyunHttpdns.getSessionId();
print("SessionId = $sessionId");
No parameters are required. Returns the current session ID.
5.6. Clear cache
Clears the DNS resolution cache.
// Clear all caches
await AliyunHttpdns.cleanHostCache(null);
// Clear the cache for a specified domain name
await AliyunHttpdns.cleanHostCache(['www.aliyun.com']);
5.7. Auto-refresh pre-resolved domains on network change
Automatically refreshes pre-resolved domain caches when the network environment changes. Set through initialization configuration.
final config = AliyunHttpdnsConfig(
accountId: Your AccountId,
secretKey: 'your_secret_key',
preResolveAfterNetworkChanged: true, // Auto-refresh on network change
);
await AliyunHttpdns.init(config);
5.8. Persistent cache configuration
When enabled, the SDK saves resolution results locally. After app restart, cached results load from the device. Set through initialization configuration.
final config = AliyunHttpdnsConfig(
accountId: Your AccountId,
secretKey: 'your_secret_key',
persistentCacheEnabled: true, // Enable persistent cache
discardExpiredAfterSeconds: 86400, // Optional, discard cache expired for more than 1 day
);
await AliyunHttpdns.init(config);
Parameters:
|
Parameter Name |
Type |
Required |
Features |
|
persistentCacheEnabled |
bool |
Optional parameters |
Specifies whether to enable the persistent cache. Default: false. |
|
discardExpiredAfterSeconds |
int? |
Optional parameters |
The expiration threshold in seconds. When the app starts, it discards cached records that have been expired for longer than this duration. |
5.9 IP Preference
Enables IP ranking for specified domains. The SDK runs TCP speed tests on resolved IPs and sorts them by availability. Set through initialization configuration:
final config = AliyunHttpdnsConfig(
accountId: Your AccountId,
secretKey: 'your_secret_key',
ipRankingDatasource: {
'www.aliyun.com': 443,
},
);
await AliyunHttpdns.init(config);
Parameters:
|
Parameter name |
Type |
Required |
Features |
|
ipRankingDatasource |
Map<String, int>? |
Optional parameters |
A map of domain names and ports, such as {'www.aliyun.com': 443}. |
5.10 Custom TTL
Set a callback to modify the TTL of resolution results.
AliyunHttpdns.setTtlChanger((host, ipType, ttl) {
// Return the modified TTL
return ttl * 2;
});
5.11 SDNS global parameters
Sets global SDNS parameters carried by all resolution requests.
AliyunHttpdns.setSdnsGlobalParams({
'key1': 'value1',
'key2': 'value2',
});
5.12 Correct signature time
Calibrates the client time when it differs from the server time.
AliyunHttpdns.setAuthCurrentTime(serverTimestamp);
6. Version upgrade guide
6.1 Guide to upgrading from version 1.x to 2.0.0
Version 2.0.0 is a pure Dart rewrite with these advantages:
-
No Android or iOS native SDK dependencies — simplifies configuration and version management.
-
Consistent cross-platform behavior — easier debugging and maintenance.
-
Reduced package size and no native bridge overhead.
This upgrade involves API changes in the initialization method and parameter types. Follow these steps:
Detailed upgrade steps
1. Update the dependency version
pubspec.yaml
dependencies:aliyun_httpdns: ^2.0.0
Run the update:
flutter pub upgrade aliyun_httpdns
Version 2.0.0 is a pure Dart implementation. You can delete configurations related to the native SDK in your project, such as the HTTPDNS dependency in build.gradle and the AlicloudHTTPDNS dependency in podspec.
2. Refactor the initialization code
Before upgrade (1.x)
// 1.x: Two-stage initialization
await AliyunHttpdns.init(
accountId: Your AccountId,
secretKey: "your_secret_key",
aesSecretKey: "your_aes_key",
);
await AliyunHttpdns.setHttpsRequestEnabled(true);
await AliyunHttpdns.setPersistentCacheIPEnabled(true);
await AliyunHttpdns.setReuseExpiredIPEnabled(true);
await AliyunHttpdns.setPreResolveAfterNetworkChanged(true);
await AliyunHttpdns.setIPRankingList({'www.aliyun.com': 443});
await AliyunHttpdns.build();
After upgrade (2.0)
final config = AliyunHttpdnsConfig(
accountId: Your AccountId,
secretKey: 'your_secret_key',
aesSecretKey: 'your_aes_key',
httpsEnabled: true,
persistentCacheEnabled: true,
reuseExpiredIPEnabled: true,
preResolveAfterNetworkChanged: true,
ipRankingDatasource: {'www.aliyun.com': 443},
);
await AliyunHttpdns.init(config);
Notes:
-
All feature configurations are merged into the
AliyunHttpdnsConfigconstructor parameters. -
You no longer need to call the
build()method. -
New configuration parameters such as
region,timeout, anddiscardExpiredAfterSecondsare added.
3. Update the resolution API
Before upgrade (1.x)
final res = await AliyunHttpdns.resolveHostSyncNonBlocking(
'www.aliyun.com',
ipType: 'both',
);
final ipv4s = res['ipv4'] ?? [];
final ipv6s = res['ipv6'] ?? [];
After upgrade (2.0)
final result = await AliyunHttpdns.resolveHostSyncNonBlocking(
'www.aliyun.com',
ipType: HttpdnsIpType.auto,
);
final ipv4s = result?.ips ?? [];
final ipv6s = result?.ipv6s ?? [];
Notes:
-
ipTypeis changed from a string to theHttpdnsIpTypeenumeration (auto, v4, v6, both). -
The return value is changed from
Map<String, List<String>>to aResolveResult?object. -
The field names are changed from
ipv4/ipv6toips/ipv6s. -
Two new resolution methods,
resolveHostSyncandresolveHostAsync, are added.
4. Update the pre-resolution API
Before upgrade (1.x)
await AliyunHttpdns.setPreResolveHosts(['www.aliyun.com']);
After upgrade (2.0)
await AliyunHttpdns.setPreResolveHosts(['www.aliyun.com']);
5. Add a custom log handler
AliyunHttpdns.setLogHandler((message) {
print(message);
});
6. Update the clear cache API
Before upgrade (1.x)
await AliyunHttpdns.cleanAllHostCache();
After upgrade (2.0)
// Clear all caches
await AliyunHttpdns.cleanHostCache(null);
// Clear the cache for a specified domain name (new)
await AliyunHttpdns.cleanHostCache(['www.aliyun.com']);
If your application does not use any of the changed APIs, you do not need to take any action.
API upgrade mapping table (1.x → 2.0)
|
API category |
1.x |
2.0 |
|
Initialization |
|
|
|
Enable HTTPS requests |
|
|
|
Enable expired IPs |
|
|
|
Enable local cache |
|
|
|
Pre-resolve on network change |
|
|
|
Preferred IP |
|
|
|
Build service |
|
Not required |
|
Synchronous non-blocking resolution |
|
|
|
Synchronous blocking resolution |
None |
|
|
Asynchronous callback resolution |
None |
|
|
Return value |
|
|
|
Set pre-resolve hosts |
|
|
|
Clear cache |
|
|
|
Custom TTL |
None |
|
|
SDNS global parameters |
None |
|
|
Custom log handler |
None |
|
|
Correct signature time |
None |
|
6.2 Guide to upgrading from version 0.x to 1.0.0
Version 1.0.0 introduces a comprehensive architectural refactoring:
-
Unified configuration: Moves from scattered runtime configurations to a two-stage initialization pattern (init + build), resolving configuration timing issues.
-
Standardized resolution API: Provides a unified
resolveHostSyncNonBlockingmethod that returns structured data instead of JSON strings. -
Static methods: Switches from a singleton pattern to static method calls — no instance creation required.
-
Performance optimization: Improves resolution performance and resource utilization through internal enhancements.
This is a backward-incompatible change. You only need to modify the APIs that your application uses. Refer to the upgrade steps and API mapping table below.
Detailed upgrade steps
1. Update the dependency version
pubspec.yaml
dependencies:aliyun_httpdns: ^1.0.0
Run the update:
flutter pub upgrade aliyun_httpdns
2. Refactor the initialization code
Before upgrade
// Old version: Singleton pattern + one-step initialization
final _aliyunHttpDns = AliyunHttpDns();
await _aliyunHttpDns.init(
"YOUR_ACCOUNT_ID", // String type
secretKey: "your_secret_key",
aesSecretKey: "your_aes_key",
region: "",
timeout: 2000,
enableHttps: true,
enableExpireIp: true,
enableCacheIp: true,
enableDegradationLocalDns: true,
preResolveAfterNetworkChanged: true,
ipRankingMap: {"www.aliyun.com": 80},
sdnsGlobalParam: {"aa": "bb"},
bizTags: ["tag1", "tag2"]
);
After upgrade
// New version: Static methods + two-stage initialization
// Stage 1: Initialize basic configurations
await AliyunHttpdns.init(
accountId: your_account_id, // int type, required
secretKey: "your_secret_key", // Optional
aesSecretKey: "your_aes_key", // Optional
);
// Stage 2: Set feature options
await AliyunHttpdns.setHttpsRequestEnabled(true); // Replaces enableHttps
await AliyunHttpdns.setLogEnabled(true); // Replaces enableLog
await AliyunHttpdns.setPersistentCacheIPEnabled(true); // Replaces enableCacheIp
await AliyunHttpdns.setReuseExpiredIPEnabled(true); // Replaces enableExpireIp
await AliyunHttpdns.setPreResolveAfterNetworkChanged(true); // Replaces preResolveAfterNetworkChanged
// Stage 3: Build the service (must be called)
await AliyunHttpdns.build();
Notes:
-
The
region,timeout,enableDegradationLocalDns,ipRankingMap,sdnsGlobalParam, andbizTagsparameters have been removed. -
A new
build()method has been added. It must be called after configuration is complete. -
All methods are now static. You do not need to create an instance.
3. Update the resolution API
Before upgrade
// Synchronous non-blocking, returns a JSON string
String result = await _aliyunHttpDns.resolve(
"YOUR_ACCOUNT_ID", // accountId
"www.aliyun.com", // host
kRequestIpv4AndIpv6, // requestIpType
);
// Requires manual JSON parsing
Map<String, dynamic> map = json.decode(result);
List<String> ipv4s = List<String>.from(map['ipv4'] ?? []);
List<String> ipv6s = List<String>.from(map['ipv6'] ?? []);
// Use the first IP
String ip = ipv4s.isNotEmpty ? ipv4s.first : '';
After upgrade
// Synchronous non-blocking, returns structured data
Map<String, List<String>> result = await AliyunHttpdns.resolveHostSyncNonBlocking(
'www.aliyun.com', // hostname (accountId is not required)
ipType: 'both', // Replaces kRequestIpv4AndIpv6
);
// Get the IP list directly
List<String> ipv4s = result['ipv4'] ?? [];
List<String> ipv6s = result['ipv6'] ?? [];
// Use the first IP
String ip = ipv4s.isNotEmpty ? ipv4s.first : '';
Custom resolution parameters:
// Before upgrade
String result = await _aliyunHttpDns.resolve(
"YOUR_ACCOUNT_ID",
"www.aliyun.com",
kRequestIpv4AndIpv6,
params: {"key": "value"},
cacheKey: "custom_key"
);
// After upgrade
Map<String, List<String>> result = await AliyunHttpdns.resolveHostSyncNonBlocking(
'www.aliyun.com',
ipType: 'both',
sdnsParams: {"key": "value"}, // Parameter name changed
cacheKey: "custom_key"
);
4. Update the pre-resolution API
Before upgrade
await _aliyunHttpDns.setPreResolveHosts(
"YOUR_ACCOUNT_ID", // accountId
["www.aliyun.com"],
kRequestIpv4AndIpv6 // requestIpType
);
After upgrade
await AliyunHttpdns.setPreResolveHosts(
["www.aliyun.com"], // accountId is not required
ipType: 'both' // Replaces kRequestIpv4AndIpv6
);
5. Update the log configuration
Before upgrade
await _aliyunHttpDns.enableLog(true);
After upgrade
await AliyunHttpdns.setLogEnabled(true);
6. Update SessionId retrieval
Before upgrade
String sessionId = await _aliyunHttpDns.getSessionId("YOUR_ACCOUNT_ID");
After upgrade
String? sessionId = await AliyunHttpdns.getSessionId();
7. Use new features
Clear cache
await AliyunHttpdns.cleanAllHostCache();
Persistent cache configuration
await AliyunHttpdns.setPersistentCacheIPEnabled(true);
If your application does not use any of the incompatible APIs, you do not need to take any action.
API upgrade mapping table
|
API category |
Before upgrade |
After upgrade |
|
Create instance |
|
Not required. Use static methods directly. |
|
Initialization |
|
|
|
Build service |
None |
|
|
Enable HTTPS requests |
|
|
|
Enable expired IPs |
|
|
|
Enable local cache |
|
|
|
Pre-resolve on network change |
|
|
|
Control log output |
|
|
|
Synchronous non-blocking resolution |
|
|
|
IPv4 resolution |
|
|
|
IPv6 resolution |
|
|
|
IPv4 and IPv6 resolution |
|
|
|
Auto-select |
None |
|
|
Custom resolution parameters |
|
|
|
Set pre-resolve hosts |
|
|
|
Get SessionId |
|
|
|
Clear cache |
None |
|
|
Correct signature time |
|
Removed |