HarmonyOS NEXT 网络请求封装实战:@kit.NetworkKit 严格模式范例
基于 HarmonyOS NEXT API 12+ @kit.NetworkKit (http) 编写零 any、强类型泛型、带统一错误码与超时处理的 ArkTS 网络请求客户端。
- 适用
- API 12+ (HarmonyOS NEXT)
- 更新
- 2026/12/02
严格模式网络层设计要点
在 ArkTS 中封装 HTTP 客户端,核心要避开三个雷区:
- 不要用
any声明响应体data,使用泛型ApiResponse<T>。 - 请求头与查询参数用
Record<string, string>,不要写未声明类型的对象字面量。 - 务必在
finally中释放httpRequest.destroy()——依据 OpenHarmony 官方文档,每一个http.createHttp()实例仅对应一个 HTTP 请求任务,不可复用,用完即毁可避免底层连接与原生句柄泄漏。
完整可编译封装代码
使用前请确认已在
module.json5中声明ohos.permission.INTERNET权限。
import { http } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
export interface ApiEnvelope<T> {
code: number;
message: string;
data: T;
}
export class HttpClient {
private readonly baseUrl: string;
private readonly timeoutMs: number;
constructor(baseUrl: string, timeoutMs: number = 10000) {
this.baseUrl = baseUrl;
this.timeoutMs = timeoutMs;
}
async get<T>(path: string, headers: Record<string, string> = {}): Promise<ApiEnvelope<T>> {
return this.request<T>(path, http.RequestMethod.GET, undefined, headers);
}
async post<T>(path: string, body: Object, headers: Record<string, string> = {}): Promise<ApiEnvelope<T>> {
return this.request<T>(path, http.RequestMethod.POST, body, headers);
}
private async request<T>(
path: string,
method: http.RequestMethod,
body?: Object,
customHeaders: Record<string, string> = {}
): Promise<ApiEnvelope<T>> {
const client = http.createHttp();
const mergedHeaders: Record<string, string> = {
'Content-Type': 'application/json'
};
const keys = Object.keys(customHeaders);
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
mergedHeaders[k] = customHeaders[k];
}
try {
const resp = await client.request(`${this.baseUrl}${path}`, {
method: method,
header: mergedHeaders,
extraData: body !== undefined ? JSON.stringify(body) : undefined,
expectDataType: http.HttpDataType.STRING,
connectTimeout: this.timeoutMs,
readTimeout: this.timeoutMs
});
if (resp.responseCode < 200 || resp.responseCode >= 300) {
throw new Error(`HTTP_${resp.responseCode}: 请求返回非 2xx 状态码`);
}
const text = resp.result as string;
return JSON.parse(text) as ApiEnvelope<T>;
} catch (err) {
if (err instanceof Error) {
throw err;
}
const bizErr = err as BusinessError;
throw new Error(`NETWORK_${bizErr.code}: ${bizErr.message || '网络请求失败'}`);
} finally {
client.destroy();
}
}
}
调用示例
interface VersionInfo {
latest: string;
forceUpdate: boolean;
}
const api = new HttpClient('https://api.example.com');
async function checkVersion(): Promise<void> {
const res = await api.get<VersionInfo>('/v1/app/version');
if (res.code === 0) {
console.info(`最新版本:${res.data.latest}`);
}
} 常见问题 FAQ
为什么每次请求完都要调用 httpRequest.destroy()?▾
每个 http.createHttp() 创建的实例都会占用底层连接与原生句柄,请求结束(无论成功或异常)在 finally 中调用 destroy() 是防止内存泄漏的关键。
开发者资源