This topic describes how to integrate and use HTTPDNS in Unity applications.
Unity is a platform for creating and operating real-time 3D interactive content. It helps creators in game development, art, architecture, automotive design, and film turn their ideas into reality. The Unity platform provides a complete software solution to create, operate, and monetize any real-time interactive 2D and 3D content. It supports platforms such as mobile phones, tablets, PCs, game consoles, and augmented reality (AR) and virtual reality (VR) devices.
With the increasing use of Unity to develop various types of mobile applications, we now provide a dedicated HTTPDNS plugin for Unity. This plugin helps Unity developers integrate HTTPDNS features in a familiar way.
The following sections provide instructions and best practices for using the plugin.
1. Quick Start
1.1 Activate the service
For more information about how to activate HTTPDNS, see Quick Start.
1.2 Obtain configurations
Obtain your AccountId, SecretKey, and AESSecretKey from the Development configurations page in the EMAS console. You need this information to initialize the software development kit (SDK). For more information, see Development configurations.
1.3 Integrate the plugin into your project
This plugin is provided as source code and is published on GitHub. You can integrate the plugin by copying it to your Unity project.
1.3.1 Import the Unity package
Download the
httpdns_unity_demodirectory.Copy the entire
Assets/Pluginsdirectory to your Unity project.Copy the
Assets/Editordirectory (optional, used to create a test UI) to your project.
Your project structure should look like this:
YourUnityProject/
├── Assets/
│ ├── Plugins/
│ │ ├── HttpDnsHelper.cs # Main interface file
│ │ ├── AndroidHttpDnsHelper.cs # Android platform implementation
│ │ ├── iOSHttpDnsHelper.cs # iOS platform implementation
│ │ ├── CHttpDnsHelper.cs # C SDK platform implementation
│ │ ├── Android/ # Android JAR library
│ │ ├── iOS/ # iOS Bridge file
│ │ └── C/ # C SDK
│ └── Editor/ # Test UI creator
├── ProjectSettings/
└── ...The plugin uses files such as baseProjectTemplate, mainTemplate, proguard-user, and settingsTemplate. If other parts of your project also need to customize these files, make sure to merge the changes.
1.3.2 Verify the native SDK versions
The plugin integrates the native HTTPDNS SDKs for the corresponding platforms. The current versions are:
Android:
com.aliyun.ams:alicloud-android-httpdns:2.6.5iOS:
AlicloudHTTPDNS:3.2.1C:
alibabacloud-httpdns-c-sdk:2.2.5
2. Installation and configuration
2.1 Add Unity dependencies
Make the following configurations in your Unity project:
# Unity project settings
Player Settings:
- Android:
Minimum API Level: 19+
Internet Permission: Enabled
- iOS:
Deployment Target: 12.0+
Internet Capability: Enabled
- C:
Platforms: Windows/macOS
Architectures: x64/arm64
Scripting Backend: Mono or IL2CPPThe plugin uses local source code dependencies. After you add the plugin to your project, you must configure it for the target platform.
2.2 Update native SDK versions
To update the native HTTPDNS SDK version, perform the following steps:
2.2.1 Update the Android SDK version
The Android SDK is managed through Maven dependencies. Modify the version number in the dependencies section of Assets/Plugins/Android/mainTemplate.gradle:
dependencies {
// Other dependencies...
implementation 'com.aliyun.ams:alicloud-android-httpdns:2.6.5' // Change to the required version
}Note that the API operations for Android, iOS, and C platforms may differ. For more information, see the official documentation for each platform.
After you enable custom Gradle templates (Custom Main/Base Gradle Template, Custom Proguard), Unity Build automatically pulls the corresponding version from the repository.
For available versions, see Android SDK release notes.
2.2.2 Update the iOS SDK version
Edit the CocoaPods dependency version in the post-build processor:
// Update the version in HttpDnsIOSPostProcessor.cs
podfileContent += " pod 'AlicloudHTTPDNS', '~> 3.2.1'\n";
// Update to the required version
podfileContent += " pod 'AlicloudHTTPDNS', '~> new_version_number'\n";For available versions, see iOS SDK release notes.
2.2.3 Update the C SDK version
Perform the following steps:
Download the updated C SDK source code.
Compile the source code on your local machine to generate native library files.
Place the generated library files in the plugin directory of your Unity project. For example, place the
.dllfile for Windows or the.dylibfile for macOS in theAssets/Plugins/C/x86_64/directory.Return to Unity and rebuild the project for the changes to take effect.
For more information and version details, see C SDK release notes.
2.2.4 Rebuild the project
After updating the version, you need to rebuild the project.
Android:
# In the Unity Editor
File -> Build Settings -> Android -> BuildiOS:
# After building in the Unity Editor, cd [iOS build directory]
pod install --repo-update
open Unity-iPhone.xcworkspaceC (Windows/macOS):
# In the Unity Editor
File -> Build Settings -> PC, Mac & Linux Standalone -> Build3. Configuration and usage
3.1 Initialization
After your application starts, you must initialize the plugin before you can call HTTPDNS operations. Initialization involves configuring your AccountId, SecretKey, and other feature switches. The following code provides an example:
using UnityEngine;
public class HttpDnsManager : MonoBehaviour
{
void Start()
{
// Initialize HTTPDNS - Phased initialization mode
HttpDnsHelper.init("YOUR_ACCOUNT_ID", "YOUR_SECRET_KEY");
// Set feature options
HttpDnsHelper.setHttpsRequestEnabled(true);
HttpDnsHelper.debug(true);
HttpDnsHelper.setTimeout(3000);
// Advanced feature configurations
HttpDnsHelper.setPersistentCacheIPEnabled(true, 3600); // Enable persistent cache for 1 hour
HttpDnsHelper.setReuseExpiredIPEnabled(true); // Allow reuse of expired IP addresses
HttpDnsHelper.setPreResolveAfterNetworkChanged(true); // Enable auto-preresolution on network transitions
// Build the service instance
bool success = HttpDnsHelper.build();
if (success)
{
Debug.Log("HTTPDNS initialized successfully");
// Preresolve frequently used domain names
var hosts = new List<string> { "www.aliyun.com", "ecs.console.alibabacloud.com" };
HttpDnsHelper.setPreResolveHosts(hosts, "auto");
}
else
{
Debug.LogError("HTTPDNS initialization failed");
}
}
}If you set the setHttpsRequestEnabled parameter to true, your costs increase. For more information, see Product Billing.
If you have high security requirements for domain name information or SDNS parameters, you can set the aesSecretKey parameter to enable content encryption for resolution requests. Using content encryption increases your costs. For more information, see Product Billing.
3.1.1 Log configuration
During application development, you can enable logging for HTTPDNS by calling the log output control method. The following code provides an example:
HttpDnsHelper.debug(true);
Debug.Log("Log output is enabled");3.1.2 SessionId recording
While the application is running, you can call the getSessionId method to obtain the sessionId and record it in your application's data collection system. The sessionId identifies a specific application session. You can use it to query resolution logs for a specific session during online troubleshooting. The following code provides an example:
string sessionId = HttpDnsHelper.getSessionId();
Debug.Log($"SessionId = {sessionId}");3.2 Domain name resolution
3.2.1 Preresolution
When you need to resolve a domain name in advance, you can call the pre-resolution method. The following code provides an example:
var hosts = new List<string> { "www.aliyun.com", "www.example.com" };
HttpDnsHelper.setPreResolveHosts(hosts, "both");
Debug.Log("Preresolution is set successfully");After this method is called, the plugin initiates domain name resolution and caches the result in memory for direct use in subsequent requests.
3.2.2 Domain name resolution
When you need to resolve a domain name, you can call a domain name resolution method to obtain an IP address. The following code provides an example:
public void ResolveDomain(string hostname)
{
// Synchronous non-blocking resolution
var result = HttpDnsHelper.resolveHostSyncNonBlocking(hostname, "auto");
if (result != null)
{
Debug.Log($"IPv4 addresses: {result.IPv4.Count}");
Debug.Log($"IPv6 addresses: {result.IPv6.Count}");
Debug.Log($"TTL: {result.TTL} seconds");
}
}Note: resolveHostSyncNonBlocking is a synchronous non-blocking resolution method that may return null or no result. We recommend that you use this feature with pre-resolution. If no resolution result is returned, fall back to the system DNS for the request.
4. Unity best practices
4.1 How it works
This example demonstrates a complete solution for integrating HTTPDNS in Unity:
Unified cross-platform interface: Use
HttpDnsHelperto provide a unified API.Platform-specific implementations: Provide different underlying implementations for Android, iOS, and C SDKs.
Automatic DNS replacement: Automatically replace the domain name with the resolved IP address before a network request.
Host header setting: Ensure that the Server Name Indication (SNI) is correctly set for HTTPS/SSL connections.
4.2 Network request integration
When you use different network modules to send requests, you need to configure request headers and perform other related operations. The following sections provide examples for HttpClient, HttpWebRequest, and UnityWebRequest.
4.2.1 HttpClient
using System;
using System.Net.Http;
using UnityEngine;
public class HttpDnsHttpClient : MonoBehaviour
{
private static readonly HttpClient httpClient = new HttpClient();
public async void MakeRequest(string url)
{
try
{
var uri = new Uri(url);
string hostname = uri.Host;
// Resolve the domain name using HTTPDNS
var result = HttpDnsHelper.resolveHostSyncNonBlocking(hostname, "auto");
if (result != null && result.IPv4 != null && result.IPv4.Count > 0)
{
string resolvedIP = result.IPv4[0];
string newUrl = url.Replace(hostname, resolvedIP);
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, newUrl))
{
// Important: Set the Host header to ensure SSL/SNI correctness
requestMessage.Headers.Host = hostname;
var response = await httpClient.SendAsync(requestMessage);
string content = await response.Content.ReadAsStringAsync();
Debug.Log($"Request successful: {response.StatusCode}");
}
}
}
catch (Exception e)
{
Debug.LogError($"Request failed: {e.Message}");
}
}
}4.2.2 HttpWebRequest
using System;
using System.IO;
using System.Net;
using UnityEngine;
public class HttpDnsWebRequest : MonoBehaviour
{
public void MakeRequest(string url)
{
try
{
var uri = new Uri(url);
string hostname = uri.Host;
// Resolve the domain name using HTTPDNS
var result = HttpDnsHelper.resolveHostSyncNonBlocking(hostname, "auto");
if (result != null && result.IPv4 != null && result.IPv4.Count > 0)
{
string resolvedIP = result.IPv4[0];
string newUrl = url.Replace(hostname, resolvedIP);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newUrl);
request.Method = "GET";
// Important: Set the Host header to ensure SSL/SNI correctness
request.Host = hostname;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string content = reader.ReadToEnd();
Debug.Log($"Request successful: {response.StatusCode}");
}
}
}
catch (Exception e)
{
Debug.LogError($"Request failed: {e.Message}");
}
}
}4.2.3 UnityWebRequest (Not recommended)
UnityWebRequest cannot correctly configure SNI. If the server relies on SNI to return a specific domain name certificate, SSL authentication fails. Therefore, we recommend that you use the first two network request methods to handle these domain names.
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class HttpDnsUnityWebRequest : MonoBehaviour
{
public IEnumerator MakeRequest(string url)
{
var uri = new Uri(url);
string hostname = uri.Host;
// Resolve the domain name using HTTPDNS
var result = HttpDnsHelper.resolveHostSyncNonBlocking(hostname, "auto");
if (result != null && result.IPv4 != null && result.IPv4.Count > 0)
{
string resolvedIP = result.IPv4[0];
string newUrl = url.Replace(hostname, resolvedIP);
using (UnityWebRequest request = UnityWebRequest.Get(newUrl))
{
// Important: Set the Host header
request.SetRequestHeader("Host", hostname);
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
Debug.Log($"Request successful: {request.responseCode}");
}
else
{
Debug.LogError($"Request failed: {request.error}");
}
}
}
}
}4.3 Use the test UI
The project provides two test UI creators:
Basic Test UI: Create it from the
HttpDNS/Create DNS Test UImenu.Advanced Test UI: Create it from the
HttpDNS/Create Advanced Test UImenu.
The test UI includes a complete feature demo to help you quickly verify the integration.
5. API reference
5.1 Initialization methods
init
Initializes the HTTPDNS service.
// Basic initialization
HttpDnsHelper.init(string accountId, string secretKey);
// Complete initialization
HttpDnsHelper.init(string accountId, string secretKey, string aesSecretKey);Parameters:
accountId: The HTTPDNS account ID (Required).secretKey: The AccessKey pair (Optional, used for authentication).aesSecretKey: The AES encryption key (Optional, used for encryption).
If you have high security requirements for domain name information or SDNS parameters, you can set the aesSecretKey parameter to enable content encryption for resolution requests. Using content encryption increases your costs. For more information, see Product Billing.
build
Builds the HTTPDNS service instance. Call this method after setting all configurations.
bool success = HttpDnsHelper.build();Return value:
true: The instance is built successfully.false: The instance failed to be built.
5.2 Configuration methods
debug
Controls whether to print debug logs.
HttpDnsHelper.debug(bool enable);setHttpsRequestEnabled
Sets whether to use HTTPS for DNS queries.
HttpDnsHelper.setHttpsRequestEnabled(bool enable);If you set the setHttpsRequestEnabled parameter to true, your costs increase. For more information, see Product Billing.
setTimeout
Sets the timeout period for DNS queries.
HttpDnsHelper.setTimeout(int timeoutMs);setPersistentCacheIPEnabled
Sets whether to enable persistent caching.
HttpDnsHelper.setPersistentCacheIPEnabled(bool enable, int cacheTTL);Parameters:
enable: Specifies whether to enable the feature.cacheTTL: The cache time to live (TTL) in seconds.
setReuseExpiredIPEnabled
Sets whether to allow the reuse of expired IP addresses.
HttpDnsHelper.setReuseExpiredIPEnabled(bool enable);setPreResolveAfterNetworkChanged
Sets whether to automatically refresh pre-resolved domain names when the network changes.
HttpDnsHelper.setPreResolveAfterNetworkChanged(bool enable);5.3 Resolution methods
getIpsByHostAsync
Asynchronously resolves a domain name.
List<string> ips = HttpDnsHelper.getIpsByHostAsync(string hostname);Returns: A list of IP addresses. If the resolution fails, it returns null or an empty list.
getIpsByHost
Synchronously resolves a domain name.
List<string> ips = HttpDnsHelper.getIpsByHost(string hostname);resolveHostSyncNonBlocking
Performs a synchronous, non-blocking resolution and returns detailed information.
HttpDnsResult result = HttpDnsHelper.resolveHostSyncNonBlocking(string hostname, string ipType);Parameters:
hostname: The domain name to resolve.ipType: The IP address type ("auto", "ipv4", "ipv6", or "both").
The returned object contains:
IPv4: A list of IPv4 addresses.IPv6: A list of IPv6 addresses.TTL: The cache TTL.Extra: Extra information.
5.4 Preresolution methods
setPreResolveHosts
Sets a list of domain names to pre-resolve.
// Single domain name
HttpDnsHelper.setPreResolveHosts(string hostname);
// Multiple domain names
HttpDnsHelper.setPreResolveHosts(List<string> hostnames, string ipType);5.5 Cache management
clearCache
Clears the cache for a specified domain name.
HttpDnsHelper.clearCache();cleanAllHostCache
Clears the cache for all domain names.
HttpDnsHelper.cleanAllHostCache();5.6 Helper methods
getSessionId
Retrieves the current session ID.
string sessionId = HttpDnsHelper.getSessionId();6. FAQ
6.1 Android build issues
Problem: Gradle cannot resolve the com.aliyun.ams:alicloud-android-httpdns dependency or the build fails.
Solution:
Enable custom Gradle templates (Player Settings -> Publishing Settings -> Custom Main/Base Gradle Template).
Check the
Assets/Plugins/Android/mainTemplate.gradlefile:Verify that the
repositoriessection is configured with the Alibaba Cloud remote repository mirror.Verify that the
dependenciessection containsimplementation 'com.aliyun.ams:alicloud-android-httpdns:version_number'.
6.2 iOS build issues
Problem: CocoaPods dependencies cannot be found after an iOS build.
Solution: Make sure to run the pod install command as described in the build instructions. Then, open the project using the .xcworkspace file.
6.3 C SDK platform issues
Problem: The C SDK platform is missing native library dependencies.
Solution:
Windows: Make sure VCPKG is installed and the environment variables are set.
macOS: Make sure the Homebrew dependency libraries are installed.
Check if the post-build processor correctly copied the library files.
Manually copy the dependency libraries to the build directory.
6.4 Network request issues
Problem: An HTTPS request fails with a certificate error.
Solution: Make sure to set the correct Host header. Use the original domain name as the SNI, not the IP address.