EntryAbility 全局初始化 + 网络请求 HttpUtil 完整源码
一、EntryAbility 全局统一初始化项目启动唯一入口etsimport UIAbility from ohos.app.ability.UIAbility; import hilog from ohos.hilog; import GlobalStore from ohos:har_base/utils/store; import FileUtil from ohos:har_base/utils/file_util; import LogUtil, { LogLevel } from ohos:har_base/utils/log_util; import HttpUtil from ohos:har_base/utils/http_util; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { hilog.info(0x0001, APP_LIFE, 应用启动 onCreate); const context this.context; // 1. 给所有底层工具注入上下文 FileUtil.setContext(context); LogUtil.setContext(context); GlobalStore.setContext(context); // 2. 生产环境关闭调试日志 LogUtil.setLogLevel(LogLevel.INFO); // 3. 初始化持久化全局状态 GlobalStore.initPersistent(); // 4. 初始化网络全局配置基础域名、超时时间 HttpUtil.initBaseConfig({ baseUrl: https://api.test.com, timeout: 10000 }); LogUtil.info(EntryAbility, 全局工具初始化完成); } onForeground() { LogUtil.info(APP_LIFE, 应用切前台); } onBackground() { LogUtil.info(APP_LIFE, 应用切后台中断所有未完成网络请求); HttpUtil.abortAllRequest(); } onDestroy() { LogUtil.info(APP_LIFE, 应用销毁释放全部资源); } }二、HttpUtil 网络请求封装har_base 核心工具etsimport http from ohos.net.http; import LogUtil from ./log_util; import GlobalStore from ./store; import DialogUtil from ./dialog_util; // 全局网络基础配置 interface HttpBaseConfig { baseUrl: string; timeout: number; } // 通用响应结构 interface HttpResponseT { code: number; msg: string; data: T; } class HttpUtil { private baseConfig: HttpBaseConfig { baseUrl: , timeout: 10000 }; // 保存所有请求任务页面销毁统一中断 private requestTaskList: http.HttpRequest[] []; initBaseConfig(config: HttpBaseConfig) { this.baseConfig config; } // 生成统一请求头自动携带token private getCommonHeader(): Recordstring, string { const token GlobalStore.getstring(token); return { Content-Type: application/json;charsetutf-8, token: token }; } // 中断全部网络请求 abortAllRequest() { this.requestTaskList.forEach(task { try { task.destroy(); } catch (e) { LogUtil.warn(HttpUtil, 请求销毁异常, e); } }); this.requestTaskList []; } // 统一请求核心方法 private async requestT( url: string, method: http.RequestMethod, data?: Object ): PromiseHttpResponseT | null { // 拼接完整接口地址 let fullUrl url.startsWith(http) ? url : ${this.baseConfig.baseUrl}${url}; const httpRequest http.createHttp(); this.requestTaskList.push(httpRequest); try { DialogUtil.showLoading(); LogUtil.debug(HttpUtil, 发起${method}请求:, fullUrl, data); const res await httpRequest.request(fullUrl, { method: method, header: this.getCommonHeader(), extraData: data ? JSON.stringify(data) : undefined, connectTimeout: this.baseConfig.timeout, readTimeout: this.baseConfig.timeout }); DialogUtil.hideLoading(); const result JSON.parse(res.result.toString()) as HttpResponseT; LogUtil.debug(HttpUtil, 接口返回数据, result); // 登录失效清空登录状态跳转登录页 if (result.code 401) { LogUtil.warn(HttpUtil, token失效退出登录); GlobalStore.logout(); DialogUtil.alert({ content: 登录已过期请重新登录 }); } return result; } catch (err) { DialogUtil.hideLoading(); LogUtil.error(HttpUtil, 网络请求异常, err); DialogUtil.alert({ content: 网络请求失败请检查网络 }); return null; } } // GET 请求 getT(url: string, params?: Object): PromiseHttpResponseT | null { return this.requestT(url, http.RequestMethod.GET, params); } // POST 请求 postT(url: string, data?: Object): PromiseHttpResponseT | null { return this.requestT(url, http.RequestMethod.POST, data); } } export default new HttpUtil();三、全局弹窗工具 DialogUtilhar_base 配套工具etsimport customDialog from ohos.arkui.component.customDialog; import LogUtil from ./log_util; // 弹窗基础参数 interface AlertOpt { content: string; confirmText?: string; cancelText?: string; onConfirm?: () void; onCancel?: () void; } class DialogUtil { private dialogControllerList: customDialog.CustomDialogController[] []; // 普通提示弹窗仅确认按钮 alert(opt: AlertOpt) { const controller customDialog.show({ builder: () { Column({ space: 16 }) { Text(opt.content).fontSize(16).textAlign(TextAlign.Center) Button(opt.confirmText ?? 确定) .width(100%) .height(44) .onClick(() { controller.close(); opt.onConfirm?.(); }) } .width(90%) .padding(20) .borderRadius(12) } }); this.dialogControllerList.push(controller); } // 确认弹窗确认取消 confirm(opt: AlertOpt) { const controller customDialog.show({ builder: () { Column({ space: 16 }) { Text(opt.content).fontSize(16).textAlign(TextAlign.Center) Row({ space: 12 }) { Button(opt.cancelText ?? 取消) .layoutWeight(1) .backgroundColor(#cccccc) .onClick(() { controller.close(); opt.onCancel?.(); }) Button(opt.confirmText ?? 确认) .layoutWeight(1) .backgroundColor(#007DFF) .onClick(() { controller.close(); opt.onConfirm?.(); }) } } .width(90%) .padding(20) .borderRadius(12) } }); this.dialogControllerList.push(controller); } // 全局加载弹窗 showLoading() { const controller customDialog.show({ builder: () { Column({ space: 12 }) { Text(⟳).fontSize(32) Text(加载中...).fontSize(14) } .width(120) .height(120) .borderRadius(12) .backgroundColor(#ffffff) }, mask: true }); this.dialogControllerList.push(controller); } hideLoading() { if (this.dialogControllerList.length 0) { const last this.dialogControllerList.pop(); last?.close(); } } // 页面销毁关闭全部弹窗防止遮罩残留 closeAllDialog() { this.dialogControllerList.forEach(ctrl { try { ctrl.close(); } catch (e) { LogUtil.warn(DialogUtil, 弹窗关闭异常, e); } }); this.dialogControllerList []; } } export default new DialogUtil();四、页面标准生命周期规范示例列表页面完整模板etsimport StateView, { PageState } from ohos:har_base/components/common/StateView; import RefreshListView from ohos:har_base/components/common/RefreshListView; import DialogUtil from ohos:har_base/utils/dialog_util; import LogUtil from ohos:har_base/utils/log_util; import ThemeUtil from ohos:har_base/utils/theme; import { Note } from ohos:har_note/model/Note; import NoteDb from ohos:har_note/db/NoteRdb; // 分页结构复用 interface PageInfo { pageIndex: number; pageSize: number; isNoMore: boolean; } Entry Component struct NoteListPage { State pageState: PageState PageState.LOADING; State noteList: Note[] []; State page: PageInfo { pageIndex: 0, pageSize: 10, isNoMore: false }; async aboutToAppear() { await this.loadListData(true); } // 加载列表isRefreshtrue代表下拉刷新重置页码 async loadListData(isRefresh: boolean) { if (isRefresh) { this.page.pageIndex 0; this.page.isNoMore false; } this.pageState PageState.LOADING; try { const res await NoteDb.queryList(this.page.pageIndex, this.page.pageSize); if (isRefresh) { this.noteList res; } else { this.noteList [...this.noteList, ...res]; } if (this.noteList.length 0) { this.pageState PageState.EMPTY; } else { this.pageState PageState.CONTENT; if (res.length this.page.pageSize) { this.page.isNoMore true; } else if (!isRefresh) { this.page.pageIndex 1; } } } catch (err) { LogUtil.error(NoteList, 数据库查询失败, err); this.pageState PageState.ERROR; } } // 页面销毁统一释放资源强制规范 aboutToDisappear() { DialogUtil.closeAllDialog(); NoteDb.closeDb(); LogUtil.debug(NoteList, 页面销毁资源全部释放); } build() { const color ThemeUtil.getColor(); const size ThemeUtil.getSize(); Column() .width(100%) .height(100%) .padding(size.gapMd) .backgroundColor(color.pageBg) { Text(我的笔记) .fontSize(size.fontTitle) .fontColor(color.textPrimary) .margin({ bottom: size.gapLg }) StateView({ state: this.pageState, onRetry: () this.loadListData(true) }) { RefreshListView({ list: this.noteList, page: this.page, onRefresh: () this.loadListData(true), onLoadMore: () this.loadListData(false) }) { (item: Note) { Row() .width(100%) .padding(size.gapMd) .borderRadius(size.radiusMd) .backgroundColor(color.cardBg) { Column().layoutWeight(1) { Text(item.title) .fontSize(size.fontMain) .fontColor(color.textPrimary) Text(item.content) .fontSize(size.fontAux) .fontColor(color.textSecondary) .margin({ top: size.gapXs }) } Button(删除) .height(size.btnNormal) .backgroundColor(color.danger) .borderRadius(size.radiusSm) .onClick(() { DialogUtil.confirm({ content: 确定删除这条笔记, onConfirm: async () { await NoteDb.deleteById(item.id); await this.loadListData(true); } }) }) } } } } } } }文末补充干货CSDN 专属完整工程 module.json5 依赖配置模板har_base 无依赖jsondependencies: []业务 HAR har_note 仅依赖基础库jsondependencies: [ { name: har_base, version: 1.0.0, scope: shared } ]HSP 分包依赖基础 HAR 对应业务 HARjsondependencies: [ {name:har_base,version:1.0.0,scope:shared}, {name:har_note,version:1.0.0,scope:shared} ]entry 主模块依赖所有 HAR、HSPjsondependencies: [ {name:har_base,version:1.0.0,scope:shared}, {name:har_note,version:1.0.0,scope:shared}, {name:har_user,version:1.0.0,scope:shared}, {name:hsp_note_editor,version:1.0.0,scope:shared} ]开发规范强制总结收藏备查所有页面aboutToDisappear三件事关闭全部弹窗、释放数据库、中断网络请求所有颜色、间距、字号禁止硬编码统一读取 ThemeUtil网络请求全部使用 HttpUtil自带 Loading、token 自动携带、401 登出处理列表统一使用 RefreshListView内置下拉、上拉、防重复请求锁页面状态统一用 StateView统一加载 / 空 / 错误兜底 UI全局配置、登录、深色模式全部通过 GlobalStore 管理持久化自动落盘日志统一调用 LogUtil自动脱敏敏感信息生产环境关闭调试打印模块单向依赖禁止业务 HAR 互相引用杜绝循环依赖编译报错。

相关新闻

5分钟掌握CosyVoice:免费AI语音生成神器实战指南

5分钟掌握CosyVoice:免费AI语音生成神器实战指南

5分钟掌握CosyVoice:免费AI语音生成神器实战指南 【免费下载链接】CosyVoice Multi-lingual large voice generation model, providing inference, training and deployment full-stack ability. 项目地址: https://gitcode.com/gh_mirrors/cos/CosyVoice 还…

2026/7/22 23:06:00 阅读更多 →
速卖通违反欧盟《数字服务法》,被处 5.5 亿欧元罚款!需在 2026 年 10 月 20 日前整改

速卖通违反欧盟《数字服务法》,被处 5.5 亿欧元罚款!需在 2026 年 10 月 20 日前整改

速卖通因产品管控不力领欧盟巨额罚单速卖通(AliExpress)因未能阻止非法、不安全或假冒产品在其电商平台上销售,违反了欧洲《数字服务法》(DSA)规定,被处以 5.5 亿欧元(约合 6.29 亿美元&#xf…

2026/7/22 23:06:00 阅读更多 →
OpenHarmony API23 四层HAR+HSP分层架构实战

OpenHarmony API23 四层HAR+HSP分层架构实战

一、前言:为什么不要再写单模块鸿蒙项目?很多鸿蒙初学者、在校毕设项目、小型Demo 全部采用 单 Entry 单体开发,看似写得快,实则隐患极大:所有工具、页面、业务逻辑全部堆在 entry,代码极度混乱无分层、无规…

2026/7/22 23:06:00 阅读更多 →

最新新闻

终极指南:如何用Universal x86 Tuning Utility完全释放你的硬件性能潜力 [特殊字符]

终极指南:如何用Universal x86 Tuning Utility完全释放你的硬件性能潜力 [特殊字符]

终极指南:如何用Universal x86 Tuning Utility完全释放你的硬件性能潜力 🚀 【免费下载链接】Universal-x86-Tuning-Utility Your Hardware. Your Rules. Open. Powerful. Unrestricted Tuning. 项目地址: https://gitcode.com/gh_mirrors/un/Universa…

2026/7/22 23:48:19 阅读更多 →
爬虫转大模型:把边界和取舍讲清楚

爬虫转大模型:把边界和取舍讲清楚

聊《我用爬虫经验做了次 AI 项目,最先失效的是旧方法》之前,先说一句实在的:别急着背概念,先看它在真实项目里到底解决什么问题。摘要先把这篇文章的目标说清楚:看完之后,你应该能判断这件事值不值得做&…

2026/7/22 23:48:19 阅读更多 →
Windows 2000/XP系统进程详解与优化指南

Windows 2000/XP系统进程详解与优化指南

1. Windows 2000/XP系统进程全解析作为一名从Windows NT时代就开始折腾系统的老鸟,我至今还记得当年在Windows 2000服务器上排查进程问题的日日夜夜。今天我就来详细梳理下这两个经典系统的进程体系,这份经验对现在还在维护老旧系统的朋友应该会很有帮助…

2026/7/22 23:48:19 阅读更多 →
用 Ace Data Cloud 接入 Veo API:把一句镜头描述变成可交付的视频素材

用 Ace Data Cloud 接入 Veo API:把一句镜头描述变成可交付的视频素材

用 Ace Data Cloud 接入 Veo API:把一句镜头描述变成可交付的视频素材 过去,想做一条“看起来有制作感”的短视频,往往要先写分镜、找素材、拍摄、剪辑、调色,再反复修改。对于内容团队、电商团队、SaaS 产品团队来说,…

2026/7/22 23:47:18 阅读更多 →
磨针c盘清理官网,千万不要去李鬼网站,以防被骗

磨针c盘清理官网,千万不要去李鬼网站,以防被骗

磨针c盘清理官网,千万不要去李鬼网站,以防被骗由于磨针c盘清理效果突出,很多网站假冒磨针c盘清理的官网,这也是大家对磨针的认可,请搜索“磨针工具网站”即可找到磨针c盘清理的官网。很多电脑用户都会遇到一个棘手问题…

2026/7/22 23:47:18 阅读更多 →
Grizzly入门教程:5分钟上手Jsonnet定义Grafana仪表盘,告别手动配置

Grizzly入门教程:5分钟上手Jsonnet定义Grafana仪表盘,告别手动配置

Grizzly入门教程:5分钟上手Jsonnet定义Grafana仪表盘,告别手动配置 【免费下载链接】grizzly A utility for managing Jsonnet dashboards against the Grafana API 项目地址: https://gitcode.com/gh_mirrors/griz/grizzly Grizzly(简…

2026/7/22 23:47:18 阅读更多 →

日新闻

TI DSP系统配置模块SYSCFG详解:中断机制与主设备优先级配置实战

TI DSP系统配置模块SYSCFG详解:中断机制与主设备优先级配置实战

1. 项目概述与SYSCFG模块的核心价值在嵌入式系统,尤其是像TI C6000系列这样的高性能DSP开发中,我们常常会与芯片手册里那些密密麻麻的寄存器打交道。很多开发者可能更关注算法实现、内存优化或者外设驱动,但对于一个稳定、高效的系统而言&…

2026/7/22 0:00:26 阅读更多 →
微信Server酱:高到达率的应急通知方案实践

微信Server酱:高到达率的应急通知方案实践

1. 为什么我们需要"最次"的通知方案? 在数字化协作环境中,消息通知系统的重要性不言而喻明。但现实情况是,企业级通知方案往往需要复杂的API对接(如企业微信、钉钉、飞书),个人开发者的小项目又经…

2026/7/22 0:00:26 阅读更多 →
甲方要的“简洁“PPT,到底是简洁还是省事?

甲方要的“简洁“PPT,到底是简洁还是省事?

甲方说"简洁一点",乙方听到的是"少做几页"。甲方说"不要太复杂",乙方理解成"别放图表了"。结果交过去,甲方说"我说的简洁不是这个意思"。"简洁"这个词在PPT语境里,是…

2026/7/22 0:00:26 阅读更多 →

周新闻

Go语言静态资源打包方案对比与实践指南

Go语言静态资源打包方案对比与实践指南

1. 项目背景与核心需求在Go语言开发中,我们经常需要处理静态资源文件的打包问题。无论是Web应用的模板文件、前端资源,还是配置文件、证书等,都需要随程序一起分发。传统做法是将这些文件与编译后的二进制文件放在同一目录下,但这…

2026/7/22 8:58:19 阅读更多 →
Go语言实现高性能LDAP认证服务的架构与实践

Go语言实现高性能LDAP认证服务的架构与实践

1. 项目背景与核心价值LDAP(轻量级目录访问协议)作为企业级身份认证的黄金标准,已经服务了超过80%的财富500强公司。我在金融科技领域实施统一认证体系时,发现传统Java方案存在启动慢、内存占用高等痛点。而Go语言凭借其协程并发模…

2026/7/22 19:43:43 阅读更多 →
【AI面试官实战指南】:用ChatGPT模拟10类高频技术岗面试,3天提升应答精准度92%

【AI面试官实战指南】:用ChatGPT模拟10类高频技术岗面试,3天提升应答精准度92%

更多请点击: https://intelliparadigm.com 第一章:AI面试官实战指南的核心价值与适用场景 AI面试官并非替代人类HR的“黑箱工具”,而是以可解释、可审计、可迭代的方式,赋能招聘全链路的关键基础设施。其核心价值在于将主观经验沉…

2026/7/22 12:54:44 阅读更多 →

月新闻