HarmonyOS鸿蒙Next在ArkTS中实现网络请求封装与错误重试机制
HarmonyOS鸿蒙Next在ArkTS中实现网络请求封装与错误重试机制 如何在 ArkTS 中实现网络请求封装与错误重试机制的代码呢?
4 回复
更多关于HarmonyOS鸿蒙Next在ArkTS中实现网络请求封装与错误重试机制的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在ArkTS中实现网络请求封装,可使用@ohos.net.http模块创建HttpClient实例。通过定义统一请求方法封装GET/POST请求,设置超时和重试机制。错误重试通常结合Promise与catch处理,在特定HTTP状态码或网络异常时进行有限次重试,避免无限循环。封装后可统一处理请求头、参数序列化和响应解析,提升代码复用性。
在ArkTS中实现网络请求封装与错误重试机制,可以基于@ohos.net.http模块进行设计。以下是一个简洁的实现方案:
1. 基础网络请求封装
import http from '@ohos.net.http';
class HttpRequest {
private baseURL: string;
constructor(baseURL: string) {
this.baseURL = baseURL;
}
async request<T>(config: {
url: string,
method?: http.RequestMethod,
data?: Object,
headers?: Object
}): Promise<T> {
const httpRequest = http.createHttp();
try {
const response = await httpRequest.request(
this.baseURL + config.url,
{
method: config.method || http.RequestMethod.GET,
header: config.headers || {},
extraData: config.data || {}
}
);
if (response.responseCode === 200) {
return JSON.parse(response.result as string) as T;
} else {
throw new Error(`HTTP ${response.responseCode}`);
}
} finally {
httpRequest.destroy();
}
}
}
2. 错误重试机制实现
class RetryHttpRequest extends HttpRequest {
private maxRetries: number;
private retryDelay: number;
constructor(baseURL: string, maxRetries: number = 3, retryDelay: number = 1000) {
super(baseURL);
this.maxRetries = maxRetries;
this.retryDelay = retryDelay;
}
async requestWithRetry<T>(config: Parameters<typeof this.request>[0]): Promise<T> {
let lastError: Error;
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
try {
return await this.request<T>(config);
} catch (error) {
lastError = error;
// 非最终尝试时等待重试
if (attempt < this.maxRetries) {
await this.delay(this.retryDelay * Math.pow(2, attempt)); // 指数退避
}
}
}
throw lastError;
}
private delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
3. 使用示例
// 初始化
const api = new RetryHttpRequest('https://api.example.com', 3, 1000);
// 发起带重试的请求
try {
const data = await api.requestWithRetry<{ result: string }>({
url: '/endpoint',
method: http.RequestMethod.POST,
data: { key: 'value' }
});
console.log('Response:', data);
} catch (error) {
console.error('Request failed after retries:', error);
}
关键特性说明:
- 采用指数退避策略避免请求风暴
- 支持自定义重试次数和延迟时间
- 保持类型安全(TypeScript泛型)
- 自动释放HTTP资源
此实现提供了可复用的网络请求基础,可根据实际需求扩展超时控制、拦截器、缓存等功能。



