This topic describes how to integrate the HTTPDNS SDK in Unity.
Overview
Unity is a content creation engine. Developers can use Unity to develop 2D and 3D games, 2D and 3D applications, virtual reality (VR), augmented reality (AR), mobile applications, web frontends, and real-time movie rendering software. Unity helps creators turn ideas into reality.
To help Unity developers integrate and use the HTTPDNS software development kit (SDK), we provide the PdnsUnityDemo source code for your reference. The source code includes the HTTPDNS Unity plugin.
PdnsUnityDemo is developed using Unity 2019.4.21f1c1. The Assets/Plugins directory contains the plugin. You can also create a plugin using the Alibaba Cloud DNS SDK if required. The plugin uses customized Gradle and Proguard files. If your project also customizes these files, you must merge the content.
Integration
Import the Plugins files.
Copy the files from the Plugins folder in PdnsUnityDemo to your Unity project > Assets > Plugins folder.
Configure parameters.
AlipdnsHelper.setAccountIdAndSetAccessKeyIdAndSetAccesskeySecret("accountId","accessKeyId","accesskeySecret");
AlipdnsHelper.setCacheEnable(true);
AlipdnsHelper.setSchedulePrefetchEnable(true);
AlipdnsHelper.setIspEnable(true);
AlipdnsHelper.setMaxCacheTTL(3600);
AlipdnsHelper.setMaxNegativeCache(60);
AlipdnsHelper.setScheme(1);
AlipdnsHelper.setShortEnable(false);
AlipdnsHelper.setSpeedTestEnable(true);
AlipdnsHelper.setCacheCountLimit(100);
AlipdnsHelper.setSpeedPort(80);
// Pre-resolve domain names
List<string> list = new List<string>();
list.Add("domain.example.com");
list.Add("another.example.com");
AlipdnsHelper.setPreloadDomains(list);API reference
The interface class is AlipdnsHelper.cs.
Required parameter: `accountId`. This is the unique Account ID that is generated in the console when you register for an account.
Required parameters: `accessKeyId` and `accessKeySecret`. These parameters are generated after you enable authentication in the console. Authentication secures user identities and prevents unauthorized access.
public static void setAccountIdAndSetAccessKeyIdAndSetAccesskeySecret(string accountId,string accessKeyId,string accessKeySecret)Enable caching. After a domain name is resolved for the first time, subsequent resolutions prioritize retrieving data from the cache. This greatly improves resolution speed.
public static void setCacheEnable(bool enable)Enable or disable scheduled updates for expired cache. If this feature is enabled, the SDK automatically updates the expired cache every minute. This ensures timely cache updates but may increase DNS resolutions and client traffic.
public static void setSchedulePrefetchEnable(bool enable)Enable or disable Internet Service Provider (ISP)-specific domain name caching. If this feature is enabled, cached data is stored separately for different network environments. If this feature is disabled, the same cache is used across all networks.
public static void setIspEnable(bool enable)Set the maximum Time to Live (TTL) for the cache. The TTL of the cache will not exceed this value.
The default value is 3600 s.
public static void setMaxCacheTTL(double maxCacheTTL)Set the maximum TTL for negative caching. The TTL of the negative cache will not exceed this value.
The default value is 30 s.
public static void setMaxNegativeCache(double maxNegativeCache)Set the protocol for accessing the DNS server. You can use the
schemeproperty to specify HTTP or HTTPS. The default value ofschemeis 0 for HTTP. We recommend that you use HTTP for faster resolution. You can setschemeto 1 to use HTTPS.
public static void setScheme(int scheme)Enable or disable short mode. The DNS-over-HTTPS (DoH) JSON API for HTTPDNS returns data in either a full JSON format or a simple IP address array. By default, the SDK uses the full JSON format.
public static void setShortEnable(bool enable)Enable or disable IP address sorting. If this feature is enabled, the IP addresses in the resolution result array are sorted from fastest to slowest based on the results of speed tests.
public static void setSpeedTestEnable(bool enable)Set the cache limit. You can set the maximum number of entries in the cache. The valid range is 100 to 500.
public static void setCacheCountLimit(int cacheCountLimit)Set the port for IP address speed testing. This port is used for socket probing.
public static void setSpeedPort(int speedPort)Preload domain names. The SDK includes a caching feature. After a domain name is resolved for the first time, subsequent resolutions are significantly faster. We recommend that you preload the domain names that your application may need to resolve when the application starts.
public static void setPreloadDomains(List<string> hosts)Retrieve IP addresses from the cache for the current network environment. This method automatically detects the network environment, such as IPv4-only, IPv6-only, or dual-stack, and immediately returns a suitable list of IP addresses from the cache. If the cache is empty, or if the cache has expired and `expiredIPEnabled` is set to false, this method returns an empty list.
@param host The domain name.
@param expiredIPEnabled Specifies whether to return an expired IP address.
public static List<string> getIpsByCacheWithDomain(string host, bool expiredIPEnabled)Retrieve IPv4 addresses from the cache. This method immediately returns the IPv4 resolution result from the cache. If the cache is empty, or if the cache has expired and `expiredIPEnabled` is set to false, this method returns an empty list.
@param host The domain name.
@param expiredIPEnabled Specifies whether to return an expired IP address.
public static List<string> getIpv4ByCacheWithDomain(string host, bool expiredIPEnabled)Retrieve IPv6 addresses from the cache. This method immediately returns the IPv6 resolution result from the cache. If the cache is empty, or if the cache has expired and `expiredIPEnabled` is set to false, this method returns an empty list.
@param host The domain name.
@param expiredIPEnabled Specifies whether to return an expired IP address.
public static List<string> getIpv6ByCacheWithDomain(string host, bool expiredIPEnabled)Retrieve statistics for HTTPDNS requests. This method returns information about successful and failed requests.
public static string getRequestReportInfo()Best practices
How it works
This example shows a complete solution for integrating HTTPDNS in Unity:
Cross-platform unified interface: Uses
AlipdnsHelperto provide a unified API.Platform-specific implementation: Provides different underlying implementations for the iOS and Android SDKs.
Automatic DNS replacement: Automatically replaces the domain name with the resolved IP address before a network request.
Host header setting: Ensures that the correct Server Name Indication (SNI) is set for HTTPS/SSL connections.
Network request integration
When you use different network modules to send requests, you must configure request headers. The following sections provide examples for `HttpClient`, `HttpWebRequest`, and `UnityWebRequest`.
HttpClient
using System;
using System.Net.Http;
using UnityEngine;
public class AlipdnsHttpClient : MonoBehaviour
{
private static readonly HttpClient httpClient = new HttpClient();
public async void MakeRequest(string url)
{
try
{
var uri = new Uri(url);
string hostname = uri.Host;
// Use HTTPDNS to resolve the domain name
var result = AlipdnsHelper.getIpsByCacheWithDomain(hostname, true);
if (result != null && result.Count > 0)
{
string resolvedIP = result[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 AlipdnsWebRequest : MonoBehaviour
{
public void MakeRequest(string url)
{
try
{
var uri = new Uri(url);
string hostname = uri.Host;
// Use HTTPDNS to resolve the domain name
var result = AlipdnsHelper.getIpsByCacheWithDomain(hostname, true);
if (result != null && result.Count > 0)
{
string resolvedIP = result[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}");
}
}
}UnityWebRequest (Not recommended)
Because `UnityWebRequest` cannot correctly configure SNI information, SSL validation fails when the server relies on SNI to return a specific domain name certificate. Therefore, we recommend that you use the other two network request methods to handle this type of domain name.
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class AlipdnsUnityWebRequest : MonoBehaviour
{
public IEnumerator MakeRequest(string url)
{
var uri = new Uri(url);
string hostname = uri.Host;
// Use HTTPDNS to resolve the domain name
var result = AlipdnsHelper.getIpsByCacheWithDomain(hostname, true);
if (result != null && result.Count > 0)
{
string resolvedIP = result[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}");
}
}
}
}
}This document applies only to using the HTTPDNS SDK for Android and iOS in Unity.
For more information about how to integrate and use the HTTPDNS SDK for Android and iOS, see Android SDK development guide and iOS SDK development guide.
For the complete sample code for integrating the HTTPDNS SDK for Android and iOS in Unity, see the PdnsUnityDemo source code.