鸿蒙Next中如何进行http请求封装
在鸿蒙Next开发中,如何进行HTTP请求的封装?官方文档中是否有推荐的封装方式?请求头、参数和回调处理应该如何统一管理?能否提供一个基本的封装示例?
2 回复
鸿蒙Next里搞HTTP封装?简单!用@ohos.net.http模块,写个工具类把createHttp()包起来,加个request()方法统一处理URL和参数。记得用Promise封装,这样调用时直接await http.get('xxx'),优雅得像用筷子吃西餐!
更多关于鸿蒙Next中如何进行http请求封装的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在鸿蒙Next(HarmonyOS NEXT)中,可以使用@ohos.net.http模块进行HTTP请求封装。以下是一个基础封装示例:
import http from '@ohos.net.http';
class HttpRequest {
// GET请求封装
static async get(url: string, params?: Record<string, string>) {
let httpRequest = http.createHttp();
let options = {
method: http.RequestMethod.GET,
extraData: params,
header: { 'Content-Type': 'application/json' }
};
try {
let response = await httpRequest.request(url, options);
return response.result;
} catch (error) {
console.error('GET请求失败:', error);
throw error;
} finally {
httpRequest.destroy();
}
}
// POST请求封装
static async post(url: string, data?: object) {
let httpRequest = http.createHttp();
let options = {
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json' },
extraData: JSON.stringify(data)
};
try {
let response = await httpRequest.request(url, options);
return response.result;
} catch (error) {
console.error('POST请求失败:', error);
throw error;
} finally {
httpRequest.destroy();
}
}
}
// 使用示例
// HttpRequest.get('https://api.example.com/data', { page: '1' });
// HttpRequest.post('https://api.example.com/user', { name: 'John' });
关键点说明:
- 使用
http.createHttp()创建请求实例 - 通过
httpRequest.request()发起请求 - 必须调用
httpRequest.destroy()释放资源 - 支持GET/POST/PUT/DELETE等请求方法
- 可通过options配置超时时间、请求头等参数
注意事项:
- 需要在module.json5中声明网络权限:
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
}
}
- 建议根据业务需求增加拦截器、错误重试等高级功能

