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/10/31 1:33:29 阅读更多 →
速卖通违反欧盟《数字服务法》,被处 5.5 亿欧元罚款!需在 2026 年 10 月 20 日前整改

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

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

2026/10/27 1:52:57 阅读更多 →
OpenHarmony API23 四层HAR+HSP分层架构实战

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

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

2026/10/31 7:10:15 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年,我大部分时间都在跟浏览器标签页打交道,直到第一次把桌面应用跑起来,才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词,最开始是在某段时间频繁出现在同事的讨论里,一个用HTML…

2026/10/31 0:19:11 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介:亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档,主要面向智能锁安装人员、终端用户及售后维护者,帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件,大小4.37MB,内容结构清晰&#xff…

2026/10/31 10:20:19 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统,整车要求空载跑到8m/s,电机转速已经拉到额定点,驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令,转速纹丝不动,三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/10/31 10:20:23 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年,用它写过嵌入式驱动、做过游戏服务端,也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词,我其实挺感慨的——这门语言的难点从来不是语法多,而是知识点之间的耦合太深…

2026/10/31 0:59:28 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介:亚太天能T109滑盖智能锁产品说明书以PDF格式发布,适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开,先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能,再给出完整安装步骤&…

2026/10/31 10:30:19 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历:翻开源码注释、论文摘要或者一份专业报告,每个字都认识,连在一起却像天书。想找人聊聊,身边要么没人懂,要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型,几秒钟之后&a…

2026/10/31 9:29:43 阅读更多 →

日新闻

周新闻

月新闻

我发现了一个新思路:用 Remotion + Claude Code 像写代码一样自动化生成短视频

我发现了一个新思路:用 Remotion + Claude Code 像写代码一样自动化生成短视频

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/30 17:32:24 阅读更多 →
Windows下 Codex 中 Chrome 和 Computer Use 插件不可用问题排查及解决参考方式:TaoToken 统一 Key 配置与验证

Windows下 Codex 中 Chrome 和 Computer Use 插件不可用问题排查及解决参考方式:TaoToken 统一 Key 配置与验证

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/31 11:00:40 阅读更多 →
黑夜航拍船只数据集训练YOLOV5模型全流程解析

黑夜航拍船只数据集训练YOLOV5模型全流程解析

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/31 0:09:01 阅读更多 →