All Products
Search
Document Center

HTTPDNS:Unity integration guide

Last Updated:Nov 07, 2025

This topic describes how to integrate and use HTTPDNS in Unity application development.

Unity is a platform for creating and operating real-time 3D interactive content. Creators in fields such as game development, art, architecture, automotive design, and film use Unity to bring their ideas to life. The Unity platform provides a complete set of software solutions 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.

An increasing number of mobile applications are developed using Unity. To support these developers, we created a dedicated HTTPDNS plugin for Unity. This plugin allows developers to integrate HTTPDNS features in a familiar environment.

The following sections provide instructions and best practices for using the plugin.

1. Quick start

1.1 Activate the service

To activate HTTPDNS, see Quick Start.

1.2 Obtain configurations

To obtain information such as your AccountId, SecretKey, and AESSecretKey for SDK initialization, see Development configurations in the EMAS console.

1.3 Integrate the plugin into your project

This plugin is provided as source code and is published on GitHub. To integrate the plugin, you must copy it to your Unity project.

1.3.1 Import the Unity package

  1. Download the httpdns_unity_demo folder from the project.

  2. Copy the entire Assets/Plugins folder to your Unity project.

  3. Copy the Assets/Editor folder to your project. This step is optional and is used to create a test UI.

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/
└── ...
Important

The plugin uses the baseProjectTemplate, mainTemplate, proguard-user, and settingsTemplate files. If other parts of your project also customize these files, you must merge the changes.

1.3.2 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.5

  • iOS: AlicloudHTTPDNS:3.2.1

  • C: alibabacloud-httpdns-c-sdk:2.2.5

2. Installation and configuration

2.1 Add Unity dependencies

Configure your Unity project as follows:

# Unity project configuration
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 IL2CPP

The plugin is referenced as a local source code dependency. After you add the plugin to your project, you must configure it for your target platform.

2.2 Update the native SDK version

To update the native HTTPDNS SDK version, perform the following steps:

2.2.1 Update the Android SDK version

On Android, dependencies are managed by Maven. In the Assets/Plugins/Android/mainTemplate.gradle file, modify the version number in the dependencies block:

dependencies {
    // Other dependencies...
    implementation 'com.aliyun.ams:alicloud-android-httpdns:2.6.5' // Change to the required version
}

Note: The API capabilities differ across the Android, iOS, and C platforms. For more information, see the official API documentation for each platform.

After you enable the custom Gradle templates, such as Custom Main Gradle Template, Custom Base Gradle Template, and Custom Proguard, Unity automatically pulls the corresponding version from the repository during the build.

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 version you need
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:

  • Obtain the updated C SDK source code.

  • Compile the source code on your local machine to generate the native library file.

  • Place the generated library file into the plugin folder of your Unity project, such as the .dll file in Assets/Plugins/C/x86_64/ or the .dylib file for macOS.

  • Return to Unity and rebuild the project to apply the changes.

For more information and version details, see C SDK release notes.

2.2.4 Rebuild the project

After you update the version, you must rebuild the project.

Android:

# In the Unity Editor
File -> Build Settings -> Android -> Build

iOS:

# After building in the Unity Editor, cd to the [iOS build directory]
pod install --repo-update
open Unity-iPhone.xcworkspace

C (Windows/macOS):

# In the Unity Editor
File -> Build Settings -> PC, Mac & Linux Standalone -> Build

3. Configuration and usage

3.1 Initialization and configuration

After the application starts, you must initialize the plugin before you can use HTTPDNS features. During initialization, you must configure your AccountId and SecretKey, and enable the required features. 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);
        
        // Configure advanced features
        HttpDnsHelper.setPersistentCacheIPEnabled(true, 3600); // Enable persistent cache for 1 hour
        HttpDnsHelper.setReuseExpiredIPEnabled(true);          // Allow reuse of expired IPs
        HttpDnsHelper.setPreResolveAfterNetworkChanged(true);  // Automatically pre-resolve upon network transition
        
        // Build the service instance
        bool success = HttpDnsHelper.build();
        if (success) 
        {
            Debug.Log("HTTPDNS initialized successfully");
            
            // Pre-resolve frequently used domain names
            var hosts = new List<string> { "www.aliyun.com", "ecs.console.aliyun.com" };
            HttpDnsHelper.setPreResolveHosts(hosts, "auto");
        }
        else 
        {
            Debug.LogError("HTTPDNS initialization failed");
        }
    }
}

3.1.1 Log configuration

During application development, you can call the log output control method to enable logging. The following code provides an example:

HttpDnsHelper.debug(true);
Debug.Log("Log output enabled");

3.1.2 Session ID recording

While the application is running, you can call the method to retrieve the session ID and record it in your application's data collection system. The session ID identifies a specific run of the application. You can use the session ID to query resolution logs for that run when you troubleshoot issues online. The following code provides an example:

string sessionId = HttpDnsHelper.getSessionId();
Debug.Log($"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-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("Pre-resolution set successfully");

After this method is called, the plugin initiates domain name resolution and caches the result in memory. Subsequent requests then use the cached result directly.

3.2.2 Domain name resolution

When you need to resolve a domain name, you can call a resolution method to obtain the 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 an empty result. We recommend that you use this method with the pre-resolution feature. If no result is returned, you must fall back to the system DNS for the request.

4. Best practices for Unity

4.1 How it works

This example shows a complete solution for integrating HTTPDNS in Unity:

  1. Unified cross-platform API: A unified API is provided through HttpDnsHelper.

  2. Platform-specific implementation: Different underlying implementations are provided for the Android, iOS, and C SDKs.

  3. Automatic DNS replacement: The domain name is automatically replaced with the resolved IP address before a network request is sent.

  4. Host header setting: The Host header is set to ensure the correctness of Server Name Indication (SNI) for HTTPS and SSL connections.

4.2 Network request integration

When you use different network modules to send requests, you must configure request headers. The following examples show how to do this 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)

Important

UnityWebRequest does not correctly configure Server Name Indication (SNI) information. If the server relies on SNI to return a specific domain name certificate, SSL authentication fails. Therefore, we recommend that you use HttpClient or HttpWebRequest 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:

  1. Basic Test UI: Create this UI from the HttpDNS/Create DNS Test UI menu.

  2. Advanced Test UI: Create this UI from the HttpDNS/Create Advanced Test UI menu.

The test UI includes a complete feature demo that helps 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);

// Full initialization
HttpDnsHelper.init(string accountId, string secretKey, string aesSecretKey);

Parameters:

  • accountId: Your HTTPDNS account ID. This parameter is required.

  • secretKey: The AccessKey pair. This parameter is optional and is used for authentication.

  • aesSecretKey: The AES encryption key. This parameter is optional and is used for encryption.

build

Builds the HTTPDNS service instance. You must call this method after you complete all configurations.

bool success = HttpDnsHelper.build();

Return value:

  • true: The instance is successfully built.

  • false: The instance failed to build.

5.2 Configuration methods

debug

Enables or disables the printing of debug logs.

HttpDnsHelper.debug(bool enable);

setHttpsRequestEnabled

Specifies whether to use an HTTPS request for a DNS query.

HttpDnsHelper.setHttpsRequestEnabled(bool enable);

setTimeout

Sets the timeout period for a DNS query.

HttpDnsHelper.setTimeout(int timeoutMs);

setPersistentCacheIPEnabled

Specifies whether to enable persistent cache.

HttpDnsHelper.setPersistentCacheIPEnabled(bool enable, int cacheTTL);

Parameters

  • enable: Specifies whether to enable the feature.

  • cacheTTL: The cache time to live (TTL) in seconds.

setReuseExpiredIPEnabled

Specifies whether to allow the reuse of expired IP addresses.

HttpDnsHelper.setReuseExpiredIPEnabled(bool enable);

setPreResolveAfterNetworkChanged

Specifies whether to automatically refresh pre-resolved domain names after a network transition.

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, this method returns null or an empty list.

getIpsByHost

Synchronously resolves a domain name.

List<string> ips = HttpDnsHelper.getIpsByHost(string hostname);

resolveHostSyncNonBlocking

Performs 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. Valid values are "auto", "ipv4", "ipv6", and "both".

The returned object contains:

  • IPv4: A list of IPv4 addresses.

  • IPv6: A list of IPv6 addresses.

  • TTL: The cache time to live.

  • Extra: Extra information.

5.4 Pre-resolution methods

setPreResolveHosts

Sets the 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.

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

Issue: Gradle cannot resolve the com.aliyun.ams:alicloud-android-httpdns dependency or the build fails.

Solution:

  1. Enable custom Gradle templates. Go to Player Settings > Publishing Settings and select Custom Main Gradle Template and Custom Base Gradle Template.

  2. Check the Assets/Plugins/Android/mainTemplate.gradle file to ensure the following:

    • The repositories block is configured with the Alibaba Cloud remote repository mirror.

    • The dependencies block contains implementation 'com.aliyun.ams:alicloud-android-httpdns:version_number'.

6.2 iOS build issues

Issue: The CocoaPods dependency cannot be found after an iOS build.

Solution: Make sure that you run the pod install command as described in the build instructions. Then, use the .xcworkspace file to open the project.

6.3 C SDK platform issues

Issue: The native library dependency is missing for the C SDK platform.

Solution:

  1. Windows: Make sure that VCPKG is installed and the environment variables are set correctly.

  2. macOS: Make sure that the Homebrew dependency libraries are installed.

  3. Check whether the post-build processor correctly copied the library files.

  4. Manually copy the dependency libraries to the build directory.

6.4 Network request issues

Issue: An HTTPS request fails with a certificate error.

Solution: Make sure that the Host header is set correctly. For SNI, you must use the original domain name instead of the IP address.