This topic describes how to use DNS-over-HTTPS (DoH) with the HarmonyOS native network library, Remote Communication Kit (RCP), and ArkWeb (WebView).
1. Introduction
On the HarmonyOS platform, we recommend using the HarmonyOS software development kit (SDK) to connect. For more information, see the HarmonyOS SDK Manual or . If you cannot import the SDK, you can connect using DoH. This topic describes how to connect using DoH for the following network libraries and components in HarmonyOS:
HarmonyOS network components support only one DoH link. To improve service stability, implement a fallback to local DNS.
The Network Kit and RCP libraries do not support automatic fallback to local DNS. You must implement the fallback in your application. For an example, see the sample code.
You can enable automatic fallback to Local DNS in ArkWeb by setting
<a href="https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-webview-V5#securednsmode10" id="1b0b1b228b7jm">SecureDnsMode</a>toAUTO.
The DoH configuration for Network Kit and RCP is affected by custom resolution rules that are set using
<a href="https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-net-connection-V5#connectionaddcustomdnsrule11-1" id="424d8cdeddks7">addCustomDnsRule</a>. If you use<a href="https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-net-connection-V5#connectionaddcustomdnsrule11-1" id="4c3da21d56ymi">addCustomDnsRule</a>to configure resolution for specific domain names, those domain names will not be resolved using DoH.
2. Prerequisites
Before you connect to network libraries or components in HarmonyOS using DoH, make sure that you have configured the DoH service.
3. Connect to DoH using Network Kit (httpRequest)
You can use Network Kit to enable DNS-over-HTTPS (DoH) for a single request by setting the options.dnsOverHttps: string parameter of http.request(options: <a href="https://developer.huawei.com/consumer/en/doc/harmonyos-references/js-apis-http#httprequestoptions" id="fa498210ee5q6">http.RequestOptions</a>) to your DoH endpoint. This operation does not modify the global session. The following sample code provides an example:
import http from '@ohos.net.http';
const httpRequest: http.HttpRequest = http.createHttp();
// Replace this with your DoH URL
const DOH_ENDPOINT = 'https://xxxxx.aliyunhttpdns.com/dns-query';
const isDoHFailure = (err: ErrorDetails): boolean => {
const code = String(err.code ?? '');
const msg = String(err.message ?? '');
return /(couldn'?t\s+resolve\s+host\s+name|resolve\s+host\s+name|dns|resolve|name\s*not\s*resolved|EAI_AGAIN)/i.test(msg) || /DNS/i.test(code);
};
httpRequest.request(this.urlInput, {
method: http.RequestMethod.GET,
connectTimeout: 3000,
readTimeout: 3000,
dnsOverHttps: DOH_ENDPOINT,
}).then((res: http.HttpResponse) => {
console.log('DoH request success:', res);
}).catch((err: ErrorDetails) => {
if (isDoHFailure(err)) {
console.error('DoH request error, falling back to local DNS:', err);
httpRequest.request(this.urlInput, {
method: http.RequestMethod.GET,
connectTimeout: 3000,
readTimeout: 3000,
}).then((fallbackRes: http.HttpResponse) => {
console.log('Fallback request success:', fallbackRes);
}).catch((fallbackErr: ErrorDetails) => {
console.error('Fallback request error:', fallbackErr);
});
} else {
console.error('Request error:', err);
}
});4. Connect to DoH using Remote Communication Kit (RCP)
The RCP network library supports DoH connections at two levels of granularity: global Session and individual Request. This topic describes both connection types.
4.1 Connect to DoH at the session level
You can use RCP to enable DoH at the session level by specifying your DoH endpoint in SessionConfiguration.requestConfiguration.dns.<a href="https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/remote-communication-rcp-V5#section13705867403" id="424c1e44d83tg">dnsOverHttps</a>. This operation does not modify the global session. The following code provides an example:
import { rcp } from '@kit.RemoteCommunicationKit';
import type { BusinessError } from '@ohos.base';
private isDoHFailure(err: BusinessError): boolean {
const code: string = err.code ? String(err.code) : '';
const msg: string = String(err.data);
return /(couldn'?t\s+resolve\s+host\s+name|resolve\s+host\s+name|dns|resolve|name\s*not\s*resolved|EAI_AGAIN)/i.test(msg) || /DNS/i.test(code);
}
async sendRequest() {
try {
const dohConfig: rcp.DnsOverHttpsConfiguration = {
url: 'https://xxxxx.aliyunhttpdns.com/dns-query',
skipCertificatesValidation: false,
};
const dohSession = rcp.createSession({
requestConfiguration: {
dns: { dnsOverHttps: dohConfig },
transfer: { timeout: { connectMs: 3000, transferMs: 8000 } },
},
});
const resp = await dohSession.get(this.urlInput);
console.info('DoH request success, status=', resp.statusCode);
console.info('Response:', JSON.stringify(resp));
} catch (err) {
if (this.isDoHFailure(err)) {
console.error('DoH request error, falling back to local DNS:', err);
try {
const localSession = rcp.createSession({
requestConfiguration: { transfer: { timeout: { connectMs: 3000, transferMs: 8000 } } },
});
const fb = await localSession.get(this.urlInput);
console.info('Fallback (local DNS) success, status=', fb.statusCode);
console.info('Fallback response:', JSON.stringify(fb));
} catch (fallbackErr) {
console.error('Fallback (local DNS) request error:', fallbackErr);
}
} else {
console.error('Request error (non-DoH):', err);
}
}
}4.2 Connect to DoH at the request level
You can enable DoH for a single RCP request by specifying request.configuration.dns.<a href="https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/remote-communication-rcp-V5#section9677185417382" id="da462d45103k9">dnsOverHttps</a> as the DoH endpoint, without modifying the global session. The sample code is as follows:
import { rcp } from '@kit.RemoteCommunicationKit';
import type { BusinessError } from '@ohos.base';
async sendRequest() {
try {
const dohConfig: rcp.DnsOverHttpsConfiguration = {
url: 'https://xxxxx.aliyunhttpdns.com/dns-query',
skipCertificatesValidation: false,
};
const session = rcp.createSession({
requestConfiguration: {
transfer: { timeout: { connectMs: 3000, transferMs: 8000 } },
},
});
const perReq = new rcp.Request(this.urlInput, 'GET', undefined, undefined, undefined, undefined, {
dns: { dnsOverHttps: dohConfig },
});
const resp = await session.fetch(perReq);
console.info('DoH request success, status=', resp.statusCode);
console.info('Response:', JSON.stringify(resp));
} catch (err) {
if (this.isDoHFailure(err)) {
console.error('DoH request error, falling back to local DNS:', err);
try {
const localSession = rcp.createSession({
requestConfiguration: { transfer: { timeout: { connectMs: 3000, transferMs: 8000 } } },
});
const fb = await localSession.get(this.urlInput);
console.info('Fallback (local DNS) success, status=', fb.statusCode);
console.info('Fallback response:', JSON.stringify(fb));
} catch (fallbackErr) {
console.error('Fallback (local DNS) request error:', fallbackErr);
}
} else {
console.error('Request error (non-DoH):', err);
}
}
}5. DoH policy for WebView
You can specify your DoH URL using webview.WebviewController.setHttpDns. The following code provides an example:
import { webview } from '@kit.ArkWeb';
webview.WebviewController.setHttpDns(webview.SecureDnsMode.AUTO, 'https://xxxxx.aliyunhttpdns.com/dns-query');The HarmonyOS network component supports only one DNS-over-HTTPS (DoH) link. To improve service stability, we recommend implementing a Local DNS fallback. In ArkWeb, you can set <a data-init-id="1b0b1b228b7jm" href="https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-webview-V5#securednsmode10" id="cc698912edejc">SecureDnsMode</a> to AUTO to enable an automatic fallback to Local DNS.
6. Summary
This topic describes how to integrate the DNS-over-HTTPS (DoH) feature with the HarmonyOS network library. This integration significantly improves the security and privacy protection of your application. After the configuration is complete, you can verify that DoH is working correctly. To do this, set the DNS server for your phone's Wi-Fi network to an invalid address and check whether your application can still make requests successfully.