鸿蒙Next网络请求http封装方法分享
在鸿蒙Next中开发时,如何封装HTTP网络请求?能否分享具体的实现方法和代码示例?比如如何处理请求头、参数传递、响应解析以及错误回调?希望能了解最佳实践和常见问题的解决方案。
2 回复
鸿蒙Next网络请求封装?简单!
- 创建
HttpUtil类,用@ohos.net.http搞定。 - 封装
get和post方法,参数塞进Request对象。 - 回调里处理成功/失败,记得
catch异常,别让APP崩了! - 加个
拦截器统一处理Token,优雅如老狗~
代码?下次一定!(手动狗头)
更多关于鸿蒙Next网络请求http封装方法分享的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在鸿蒙Next(HarmonyOS NEXT)中,网络请求可以通过@ohos.net.http模块实现。以下是一个简单的HTTP请求封装方法,支持GET和POST请求,便于在项目中复用:
1. 导入模块
import http from '@ohos.net.http';
2. 封装HTTP请求类
export class HttpRequest {
// GET请求
static async get(url: string, params?: Record<string, string>): Promise<any> {
let httpRequest = http.createHttp();
let options = {
method: http.RequestMethod.GET,
extraData: params, // 可选查询参数
connectTimeout: 60000,
readTimeout: 60000
};
try {
let response = await httpRequest.request(url, options);
return JSON.parse(response.result.toString());
} catch (error) {
console.error('GET请求失败:', error);
throw error;
} finally {
httpRequest.destroy();
}
}
// POST请求
static async post(url: string, data?: Record<string, Object>): Promise<any> {
let httpRequest = http.createHttp();
let options = {
method: http.RequestMethod.POST,
extraData: data, // 请求体数据
header: { 'Content-Type': 'application/json' },
connectTimeout: 60000,
readTimeout: 60000
};
try {
let response = await httpRequest.request(url, options);
return JSON.parse(response.result.toString());
} catch (error) {
console.error('POST请求失败:', error);
throw error;
} finally {
httpRequest.destroy();
}
}
}
3. 使用示例
// GET请求示例
async function fetchData() {
try {
let result = await HttpRequest.get('https://api.example.com/data', { id: 1 });
console.log('响应数据:', result);
} catch (error) {
console.error('请求异常:', error);
}
}
// POST请求示例
async function submitData() {
try {
let result = await HttpRequest.post('https://api.example.com/submit', { name: 'HarmonyOS' });
console.log('提交结果:', result);
} catch (error) {
console.error('提交失败:', error);
}
}
关键特性说明:
- 超时控制:通过
connectTimeout和readTimeout设置连接和读取超时(单位:毫秒)。 - 自动释放:使用
finally确保请求后销毁httpRequest对象,避免内存泄漏。 - 错误处理:统一捕获异常并向上抛出,便于调用方处理。
- 类型支持:使用TypeScript类型注解(如
Record<string, string>)增强代码可维护性。
注意事项:
- 需要在
module.json5中声明网络权限:{ "module": { "requestPermissions": [ { "name": "ohos.permission.INTERNET" } ] } } - 实际项目中可根据需要扩展更多功能(如拦截器、文件上传等)。
此封装提供了基础的HTTP请求能力,可根据项目需求进一步优化(如添加重试机制、缓存支持等)。

