前言在实际项目中网络请求需要统一的封装——包括请求拦截器添加 Token、响应拦截器统一错误处理、超时重试和请求取消等能力。本文以小事记xiaoshiji_ohos_app 的网络层封装为背景深入解析如何构建一个健壮的网络请求模块。本文参考 HarmonyOS 官方文档http 文档 和 application-network-reconnection.md。一、网络请求封装1.1 基本封装// 网络请求封装 import { http } from kit.NetworkKit; class HttpClient { private baseUrl: string; private token: string ; constructor(baseUrl: string) { this.baseUrl baseUrl; } setToken(token: string): void { this.token token; } async requestT(config: RequestConfig): PromiseT { const httpRequest http.createHttp(); try { // 请求拦截器添加 Token const headers { ...config.headers, Authorization: Bearer ${this.token}, Content-Type: application/json }; const response await httpRequest.request( ${this.baseUrl}${config.url}, { method: config.method || http.RequestMethod.GET, header: headers, connectTimeout: config.timeout || 5000, readTimeout: config.timeout || 10000 } ); // 响应拦截器统一错误处理 if (response.responseCode 401) { // Token 过期刷新 Token await this.refreshToken(); // 重新发起请求 return this.requestT(config); } if (response.responseCode ! 200) { throw new HttpError(response.responseCode, 请求失败); } return response.result as T; } catch (err) { // 统一错误处理 throw this.handleError(err); } finally { httpRequest.destroy(); } } }方案适用场景注意事项方案一简单场景实现简单易于维护方案二复杂场景灵活性高需注意性能方案三特殊场景针对特定需求优化二、超时重试2.1 重试机制// 超时重试实现 async function requestWithRetryT( requestFn: () PromiseT, maxRetries: number 3 ): PromiseT { let lastError: Error; for (let i 0; i maxRetries; i) { try { return await requestFn(); } catch (err) { lastError err; console.warn(请求失败第 ${i 1} 次重试); // 指数退避 await delay(Math.pow(2, i) * 1000); } } throw lastError; }三、请求取消3.1 取消请求// 取消请求 class CancellableRequest { private httpRequest: http.HttpRequest | null null; async request(url: string): Promiseany { this.httpRequest http.createHttp(); return this.httpRequest.request(url); } cancel(): void { if (this.httpRequest) { this.httpRequest.destroy(); this.httpRequest null; } } }四、常见问题4.1 请求重复发送问题用户快速点击按钮导致请求重复发送。解决方案使用防抖或取消前一个请求。五、// 错误处理示例 import { BusinessError } from kit.BasicServicesKit; try { const data await getData(https://api.example.com); } catch (err) { console.error(请求失败: ${(err as BusinessError).message}); }最佳实践策略说明效果请求拦截器统一添加 Token认证响应拦截器统一处理错误稳定超时重试指数退避可靠请求取消页面退出时取消性能八、拓展阅读本节汇总了与本文主题相关的扩展阅读材料帮助读者深入理解相关技术细节。8.1 官方文档开发者指南HarmonyOS 应用开发概述API 参考ArkTS API 参考8.2 相关技术文章性能优化最佳实践常见问题排查指南8.3 社区资源开源鸿蒙跨平台社区https://openharmonycrossplatform.csdn.net十、最佳实践与优化建议在实际开发中合理运用上述技术可以显著提升应用的性能和用户体验。以下是几个关键的最佳实践建议10.1 性能优化要点优化方向具体措施预期效果渲染性能减少不必要的组件重建提升帧率内存管理及时释放不再使用的资源降低内存占用响应速度避免在主线程执行耗时操作提升交互流畅度10.2 推荐实践步骤按照以下步骤进行优化使用 DevEco Studio 的 Profiler 工具分析当前性能瓶颈针对识别出的热点进行针对性优化通过单元测试和集成测试验证优化效果在真机环境下进行回归测试10.3 代码示例// 推荐的最佳实践示例 Component export struct OptimizedComponent { // 使用 State 管理最小粒度的状态 State private isActive: boolean false; build() { Column() { Text(this.isActive ? 激活 : 未激活) .fontSize(16) } .onClick(() { // 使用 animateTo 实现平滑过渡 animateTo({ duration: 300 }, () { this.isActive !this.isActive; }); }); } }最佳实践提示在编写代码时始终遵循 ArkUI 的性能优化原则避免在 build() 方法中执行复杂计算或频繁的状态更新。十、进一步学习与拓展掌握以上内容后可以进一步探索以下相关主题深化对 HarmonyOS 开发的理解10.1 推荐学习路径学习阶段主题预期目标基础阶段掌握核心概念和 API 用法能够独立完成基本功能开发进阶阶段理解底层原理和最佳实践能够优化应用性能和用户体验高级阶段掌握架构设计和性能调优能够主导复杂项目的技术方案10.2 实践项目建议建议通过以下实践项目巩固所学知识基于小事记项目尝试独立实现一个类似的功能模块阅读 HarmonyOS 官方 Sample 代码学习最佳实践参与开源社区贡献代码或文档10.3 相关资源HarmonyOS 官方文档提供完整的 API 参考和开发指南DevEco Studio 文档包含 IDE 使用技巧和调试方法开源社区获取项目源码和开发经验学习建议理论与实践相结合在阅读文档的同时动手编写代码才能更好地掌握 HarmonyOS 应用开发技能。总结// 网络请求示例 import { http } from kit.NetworkKit; async function getData(url: string): PromiseObject { const httpRequest http.createHttp(); const response await httpRequest.request(url); httpRequest.destroy(); return response.result; }本文深入解析了网络请求的封装策略。核心要点如下请求拦截器统一添加 Token、Content-Type 等响应拦截器统一处理错误码、Token 过期超时重试指数退避策略自动重试请求取消页面退出时取消未完成的请求如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力// 数据绑定示例 Entry Component struct DataBinding { State message: string Hello HarmonyOS; build() { Column() { Text(this.message) .fontSize(20) .fontColor(#7B68EE) } .width(100%) .height(100%) .justifyContent(FlexAlign.Center) } }// 条件渲染示例 State isVisible: boolean false; build() { Column() { if (this.isVisible) { Text(内容可见) .fontSize(16) } Button(切换) .onClick(() { this.isVisible !this.isVisible; }) } }九、完整示例代码9.1 完整组件实现以下是一个完整的组件实现示例展示了本文介绍的各个技术点的综合运用import { Component, State, Prop } from kit.ArkUI; Component export struct DemoComponent { Prop title: string ; State count: number 0; build() { Column({ space: 12 }) { // 标题区域 Text(this.title) .fontSize(18) .fontWeight(FontWeight.Bold) .fontColor(#1A1A2E) .width(100%) // 内容区域 Text(当前计数: ${this.count}) .fontSize(14) .fontColor(#6B7280) // 交互按钮 Button(点击增加) .width(120) .height(40) .backgroundColor(#7B68EE) .borderRadius(20) .fontColor(Color.White) .onClick(() { this.count; }) } .width(100%) .padding(16) .backgroundColor(Color.White) .borderRadius(12) .shadow({ radius: 4, color: #00000008, offsetX: 0, offsetY: 2 }) } }9.2 使用方式在页面中引入并使用该组件Entry Component struct Index { build() { Column() { DemoComponent({ title: 示例组件 }) } .width(100%) .height(100%) .backgroundColor(#F8F9FA) } }9.3 代码说明组件封装使用Component装饰器定义可复用的组件状态管理使用State管理组件内部状态参数传递使用Prop接收外部传入的参数事件处理使用onClick处理用户交互样式优化使用borderRadius、shadow等属性美化 UI相关资源官方文档 - 开发者指南HarmonyOS 应用开发官方文档 - ArkUI 组件参考ArkUI 组件官方文档 - API 参考API 参考官方文档 - 状态管理状态管理概述官方文档 - 动画动画概述官方文档 - 网络管理网络管理官方文档 - 数据管理数据管理开源鸿蒙跨平台社区https://openharmonycrossplatform.csdn.net