前言
在实际项目中,网络请求需要统一的封装——包括请求拦截器(添加 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 request<T>(config: RequestConfig): Promise<T> { 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.request<T>(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 requestWithRetry<T>( requestFn: () => Promise<T>, maxRetries: number = 3 ): Promise<T> { 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): Promise<any> { 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): Promise<Object> { 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