This topic describes how to integrate and use HTTPDNS in your Flutter application.
Flutter is an open-source application development framework from Google. It lets you build beautiful, natively compiled, multi-platform applications from a single codebase.
We provide an HTTPDNS plugin for the Flutter framework and explain how to integrate it with common Flutter networking frameworks. This plugin is available on GitHub and pub.dev.
The following sections provide instructions and best practices for using the plugin:
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 the development configurations in the EMAS console. You will need this information to initialize the software development kit (SDK). For more information, see Development configurations.
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: ^1.0.2 # Get the latest version number from pub.dev
dio: ^5.9.0 # Dio networking library
http: ^1.2.0 # http package
http2: ^2.3.1 # Optional, for HTTP/2 supportAfter adding the dependencies, run flutter pub get.
2.2. Native SDK version guide
2.2.1. Verify the native SDK version
The plugin integrates the native HTTPDNS SDK for each platform. The current versions are:
Android:
com.aliyun.ams:alicloud-android-httpdns:2.6.7iOS:
AlicloudHTTPDNS:3.4.0
To update the SDK version, see the update instructions below.
To update the native SDK version, import the plugin using a GitHub fork or local source code. This lets you modify the plugin's internal build.gradle or podspec file.
2.2.2. Update the Android SDK version
Edit the packages/aliyun_httpdns/android/build.gradle file and modify the dependency version:
dependencies {
implementation 'androidx.annotation:annotation:1.8.0'
// Update to your required version
implementation 'com.aliyun.ams:alicloud-android-httpdns:2.6.7'
}For available versions, see Android SDK release notes.
2.2.3. Update the iOS SDK version
Edit the packages/aliyun_httpdns/ios/aliyun_httpdns.podspec file and modify the dependency version:
Pod::Spec.new do |s|
# ... other configurations ...
s.dependency 'Flutter'
# Update to your required version
s.dependency 'AlicloudHTTPDNS', '3.4.0'
# ... other configurations ...
endFor available versions, see iOS SDK release notes.
2.2.4. Rebuild the project
After updating the version, rebuild the project:
Android:
flutter clean
flutter pub get
flutter build apk # or other build commandsiOS:
flutter clean
flutter pub get
cd ios
pod install
cd ..
flutter build ios3. Configuration and usage
3.1. Initialization configuration
After the application starts, you must initialize the plugin before you can use HTTPDNS features. The initialization process involves configuring your AccountId, SecretKey, and other settings, and enabling features. The following code provides an example:
// Initialize HTTPDNS
await AliyunHttpdns.init(
accountId: 'Your AccountId',
secretKey: 'Your SecretKey',
);
// Set feature options
await AliyunHttpdns.setHttpsRequestEnabled(true);
await AliyunHttpdns.setLogEnabled(true);
await AliyunHttpdns.setPersistentCacheIPEnabled(true);
await AliyunHttpdns.setReuseExpiredIPEnabled(true);
await AliyunHttpdns.setPreResolveAfterNetworkChanged(true);
await AliyunHttpdns.setIPRankingList({
'www.aliyun.com': 443,
});
// Build the service
await AliyunHttpdns.build();
// Set pre-resolve hosts
await AliyunHttpdns.setPreResolveHosts(['www.aliyun.com'], ipType: 'both');
print("init success");If you set the setHttpsRequestEnabled parameter to true, your billing will increase. For more information, see Product Billing.
If you have high security requirements for domain name information or SDNS parameters, you can configure the aesSecretKey parameter to enable content-layer encryption for resolution requests. Using content encryption increases your billing. For more information, see Product Billing.
3.1.1. Log configuration
To output HTTPDNS logs during application development, you can call the log output control method to enable logging. The following code provides an example:
await AliyunHttpdns.setLogEnabled(true);
print("enableLog success");3.1.2. SessionId recording
While the application is running, you can call the method to retrieve the sessionId and record it in your application's data collection system. The sessionId identifies a single application run. It can be used to query resolution logs for a specific run during online troubleshooting. The following code provides an example:
final sessionId = await AliyunHttpdns.getSessionId();
print("SessionId = $sessionId");3.2. Domain name resolution
3.2.1. Pre-resolution
When you need to resolve a domain name in advance, you can call the pre-resolve method. The following code provides an example:
await AliyunHttpdns.setPreResolveHosts(["www.aliyun.com", "www.example.com"], ipType: 'both');
print("preResolveHosts success");After the call, the plugin initiates domain name resolution and caches the result in memory. Subsequent requests can then use the cached result directly.
3.2.2. Domain name resolution
When you need to resolve a domain name, you can call the domain name resolution method to retrieve the IP address. The following code provides an example:
Future<void> _resolve() async {
final res = await AliyunHttpdns.resolveHostSyncNonBlocking('www.aliyun.com', ipType: 'both');
final ipv4List = res['ipv4'] ?? [];
final ipv6List = res['ipv6'] ?? [];
print('IPv4: $ipv4List');
print('IPv6: $ipv6List');
}4. Flutter best practices
4.1. How it works
This example shows a more direct way to integrate HTTPDNS by implementing a custom HTTP client 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 method avoids the complexity of creating a local proxy service by integrating HTTPDNS features directly at the HTTP client level.
4.2. Example
This example provides a complete Flutter application that demonstrates how to integrate HTTPDNS features.
4.2.1. Custom HTTP client adapter implementation
For the custom adapter implementation, see the lib/net/httpdns_http_client_adapter.dart file. This solution was designed and implemented by the EMAS team. If you reference this solution, please provide attribution. The adapter intercepts HTTP requests, calls HTTPDNS for domain name resolution, and uses the resolved IP address to create a socket connection.
This example supports three networking libraries: Dio, HttpClient, and the http package. The code is as follows:
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: 90);
client.maxConnectionsPerHost = 8;
}
// Configure a connection factory based on HTTPDNS
// This solution was designed and implemented by the EMAS team. Please 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 res = await AliyunHttpdns.resolveHostSyncNonBlocking(domain, ipType: 'both');
final List<String> ipv4 = res['ipv4'] ?? [];
final List<String> ipv6 = res['ipv6'] ?? [];
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
For adapter integration, see the lib/main.dart file. First, initialize HTTPDNS. Then, configure the networking library to use the custom adapter. The following code provides an example:
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 {
await AliyunHttpdns.init(
accountId: 139450,
secretKey: 'Your SecretKey',
);
await AliyunHttpdns.setHttpsRequestEnabled(true);
await AliyunHttpdns.setLogEnabled(true);
await AliyunHttpdns.setPersistentCacheIPEnabled(true);
await AliyunHttpdns.setReuseExpiredIPEnabled(true);
await AliyunHttpdns.build();
// Set pre-resolve hosts
await AliyunHttpdns.setPreResolveHosts(['www.aliyun.com'], ipType: 'both');
} catch (e) {
debugPrint('[httpdns] init failed: $e');
}
}
}When you use the configured networking library to make a request, it automatically uses 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
When the component is destroyed, you must clean up the related resources:
@override
void dispose() {
_urlController.dispose();
_httpClient.close();
_httpPackageClient.close();
super.dispose();
}5. API
5.1. Log output control
Controls whether logs are printed.
await AliyunHttpdns.setLogEnabled(true);
print("enableLog success");5.2. Initialization
Initializes the SDK. You must call this method when the application starts.
// Basic initialization
await AliyunHttpdns.init(
accountId: 139450,
secretKey: 'your_secret_key',
aesSecretKey: 'your_aes_secret_key', // Optional
);
// Configure feature options
await AliyunHttpdns.setHttpsRequestEnabled(true);
await AliyunHttpdns.setLogEnabled(true);
await AliyunHttpdns.setPersistentCacheIPEnabled(true);
await AliyunHttpdns.setReuseExpiredIPEnabled(true);
await AliyunHttpdns.setPreResolveAfterNetworkChanged(true);
await AliyunHttpdns.setIPRankingList({
'www.aliyun.com': 443,
});
// Build the service instance
await AliyunHttpdns.build();
print("init success");Initialization parameters:
Parameter | Type | Required | Features | Supported platforms |
accountId | int | Required parameters | Account ID | Android/iOS |
secretKey | String | Optional parameters | Signing key | Android/iOS |
aesSecretKey | String | Optional parameters | Encryption key | Android/iOS |
Configuration methods:
setHttpsRequestEnabled(bool)- Sets whether to use the HTTPS resolution link.setLogEnabled(bool)- Sets whether to enable logging.setPersistentCacheIPEnabled(bool)- Sets whether to enable the persistent cache.setReuseExpiredIPEnabled(bool)- Sets whether to allow the reuse of expired IP addresses.setPreResolveAfterNetworkChanged(bool)- Sets whether to automatically refresh resolutions when the network changes.setIPRankingList(hostPortMap)- Sets the list of domain names for IP ranking.
If you set the setHttpsRequestEnabled parameter to true, your billing will increase. For more information, see Product Billing.
If you have high security requirements for domain name information or SDNS parameters, you can configure the aesSecretKey parameter to enable content-layer encryption for resolution requests. Using content encryption increases your billing. For more information, see Product Billing.
5.3. Domain name resolution
Resolves a specified domain name.
Future<void> _resolve() async {
final res = await AliyunHttpdns.resolveHostSyncNonBlocking(
'www.aliyun.com',
ipType: 'both', // 'auto', 'ipv4', 'ipv6', 'both'
);
final ipv4List = res['ipv4'] ?? [];
final ipv6List = res['ipv6'] ?? [];
print('IPv4: $ipv4List');
print('IPv6: $ipv6List');
}Parameters:
Parameter | Type | Required | Features |
hostname | String | Required parameters | The domain name to resolve. |
ipType | String | Optional parameters | Requested IP type: 'auto', 'ipv4', 'ipv6', or 'both'. |
Returned data structure:
Field | Type | Features |
ipv4 | List | A list of IPv4 addresses, such as ["1.1.1.1", "2.2.2.2"]. |
ipv6 | List | A list of IPv6 addresses, such as ["::1", "::2"]. |
5.4. Pre-resolve domain names
Pre-resolves one or more domain names and caches the results in the SDK. Subsequent resolution requests for these domains can retrieve results directly from the cache, which improves resolution speed.
await AliyunHttpdns.setPreResolveHosts(
["www.aliyun.com"],
ipType: 'both'
);
print("preResolveHosts success");Parameters:
Parameter | Type | Required | Features |
hosts | List | Required parameters | A list of domain names to pre-resolve. |
ipType | String | Optional parameters | Requested IP type: 'auto', 'ipv4', 'ipv6', 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 all DNS resolution caches.
await AliyunHttpdns.cleanAllHostCache();
print("Cache cleared successfully");5.7. Auto-refresh pre-resolved domains on network change
Sets whether to automatically refresh the cache for pre-resolved domain names when the network environment changes.
await AliyunHttpdns.setPreResolveAfterNetworkChanged(true);
print("Auto-refresh on network change enabled");5.8. Persistent cache configuration
Sets whether to enable the persistent cache feature. When enabled, the SDK saves resolution results to the local device. After the app restarts, it can load the cached results from the local device.
await AliyunHttpdns.setPersistentCacheIPEnabled(true);
await AliyunHttpdns.setPersistentCacheIPEnabled(
true,
discardExpiredAfterSeconds: 86400 // Optional parameter
);
print("Persistent cache enabled");Parameters:
Parameter | Type | Required | Features |
enabled | bool | Required parameters | Specifies whether to enable the persistent cache. |
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 ranking
Specifies a list of domain names for which to perform IP ranking. When enabled, the SDK performs TCP speed tests on the resolved IP addresses and sorts them to ensure that the first IP address in the list has the best availability.
await AliyunHttpdns.setIPRankingList({
'www.aliyun.com': 443,
});
print("IP ranking configured successfully");Parameters:
Parameter | Type | Required | Features |
hostPortMap | Map<String, int> | Required Parameters | A map of domain names and ports, such as {'www.aliyun.com': 443}. |
6. Guide to upgrading from older SDKs to version 1.0.0 or later
Version 1.0.0 introduces a comprehensive architectural refactoring and API optimization. This upgrade aims to:
Unify the configuration pattern: Moves from scattered runtime configurations to a two-stage initialization pattern (init + build). This resolves configuration timing issues and improves SDK stability.
Standardize the resolution API: Redesigns the resolution API architecture to provide a unified
resolveHostSyncNonBlockingmethod. This method returns structured data instead of a JSON string.Design with static methods: Switches from a singleton pattern to static method calls. This simplifies usage and removes the need to create instances.
Optimize performance: Improves resolution performance and resource utilization efficiency through API optimization and internal implementation enhancements.
This is a major, backward-incompatible change. Although the changes are significant, you only need to modify the APIs that your application uses. The following upgrade steps and the old-to-new API mapping table can help you systematically complete this important upgrade.
Detailed upgrade steps
1. Update the dependency version
pubspec.yaml
dependencies:aliyun_httpdns: ^1.0.0Run the update:
flutter pub upgrade aliyun_httpdns2. 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 |