在鸿蒙(HarmonyOS)应用开发中,网络请求工具类通过封装底层网络操作,能显著提升代码复用性、可维护性和健壮性。以下是基于鸿蒙Next(HarmonyOS 5.0.0+)的开发实践总结:
一、工具类核心设计原则
- 统一入口管理避免业务层直接调用原生接口,减少重复代码和分散的错误处理。
- 标准化参数与响应统一处理请求头、超时设置(默认10秒)及响应数据解析(如JSON转换)。
- 异步支持与错误隔离使用Promise封装异步请求,集中捕获网络异常和逻辑错误。
二、HTTP工具类实现(基于Network Kit)
// HttpHelper.etsimport { http } from '@kit.NetworkKit';import hilog from '@ohos.hilog';// 后端统一返回数据结构export interface ResponseResult { code?: number; msg?: string; data?: Record<string, object> | Array<object>;}export interface RequestParams {}export class HttpHelper { // 创建Http请求实例 private httpRequest = http.createHttp(); /** * 通用网络请求封装 GET/POST * @param url 请求接口地址 * @param method 请求方式,默认GET * @param params 请求参数,默认空对象 无任何警告 */ async request( url: string, method: http.RequestMethod = http.RequestMethod.GET, params: RequestParams = {} as RequestParams ): Promise<ResponseResult> { try { const requestConfig: http.HttpRequestOptions = { method: method, header: { 'Content-Type': 'application/json;charset=utf-8' }, connectTimeout: 10000, // 连接超时10秒 readTimeout: 15000 // 响应超时15秒 }; const paramStr = JSON.stringify(params); if (method === http.RequestMethod.POST && paramStr !== '{}') { requestConfig.extraData = paramStr; } const response: http.HttpResponse = await this.httpRequest.request(url, requestConfig); // 校验HTTP状态码,非200抛标准Error if (response.responseCode !== 200) { throw new Error(`HTTP请求失败,状态码:${response.responseCode}`); } // 返回后端业务数据,合规类型断言 return response.result as ResponseResult; } catch (error) { const errMsg = error instanceof Error ? error.message : `网络请求异常: ${String(error)}`; hilog.error(0x0000, 'HttpHelper', `【${url}】请求失败: ${errMsg}`); throw new Error(errMsg); } } // GET请求快捷调用 async getRequest(url: string, params: RequestParams = {} as RequestParams): Promise<ResponseResult> { return this.request(url, http.RequestMethod.GET, params); } // POST请求快捷调用 async postRequest(url: string, params: RequestParams = {} as RequestParams): Promise<ResponseResult> { return this.request(url, http.RequestMethod.POST, params); } // 释放Http实例,避免内存泄漏 destroyHttp(): void { if (this.httpRequest) { this.httpRequest.destroy(); } }}
// 页面调用示例import { HttpHelper } from '../common/HttpHelper.ets';@Entry@Componentstruct DemoPage { private httpHelper = new HttpHelper(); // GET请求调用 async loadData() { try { const res = await this.httpHelper.getRequest("/api/getList", { page: 1, size: 10 }); if (res.code === 200) { console.log("请求成功:", res.data); } else { console.log("业务失败:", res.msg); } } catch (err: Error) { console.error("加载失败:", err.message); } } // POST请求调用 (支持任意嵌套参数/数组) async submitForm() { try { const formData = { name: "鸿蒙开发", age: 28, status: true, info: { id: 1001, address: "测试地址" }, list: [{ label: "选项1", value: 1 }] }; const res = await this.httpHelper.postRequest("/api/submit", formData); if (res.code === 200) { console.log("提交成功!"); } } catch (err: Error) { console.error("提交失败:", err.message); } } // 组件销毁时释放资源,必加 aboutToDisappear() { this.httpHelper.destroyHttp(); }}
四、高级方案对比
| | RCP (Remote Communication Kit) |
| | |
| | |
| http.createHttp().request() | rcp.createSession().get() |
| | |
选型建议:常规请求优先使用封装后的HTTP工具类;若遇特殊需求(如大文件下载、实时通信),可迁移至RCP方案。
五、关键注意事项
- 权限申请在
module.json5中添加网络权限: "requestPermissions": [ { "name": "ohos.permission.INTERNET" } ] - 资源释放页面销毁时主动关闭请求(如
onPageHide中调用httpRequest.destroy())。 - 异常监控结合
@ohos.hilog记录网络错误码和堆栈信息,便于定位超时(错误码28)或DNS解析失败(错误码6)等问题。
通过工具类封装,开发者可快速实现统一认证管理、自动重试机制及缓存策略集成,具体扩展可参考鸿蒙官方文档中高级网络模块。