公司动态

鸿蒙三方库 | harmony-utils之EncryptUtil URL编解码详解

📅 2026/7/28 4:45:21
鸿蒙三方库 | harmony-utils之EncryptUtil URL编解码详解
前言URL编码百分号编码用于将特殊字符转换为%XX格式确保URL中不包含非法字符。pura/harmony-utils的EncryptUtil封装了URL编解码方法。本文将从API说明、代码实战、进阶用法、常见问题等多个维度进行全面讲解帮助开发者快速掌握并应用到实际项目中。一、URL编解码核心APIEncryptUtil提供了以下URL编解码方法方法说明返回类型使用场景encodeURL(str)URL编码stringURL编码decodeURL(str)URL解码stringURL解码encodeURLComponent(str)URL组件编码string参数编码decodeURLComponent(str)URL组件解码string参数解码1.1 核心特性简洁易用封装复杂逻辑为一行调用降低使用门槛类型安全完整的TypeScript类型定义编译期即可发现错误异常处理内置异常捕获机制避免运行时崩溃双重编码支持URL整体编码和组件编码1.2 encodeURL与encodeURLComponent对比特性encodeURLencodeURLComponent编码范围保留URL结构符编码所有特殊字符保留字符?#[]不保留适用场景完整URL查询参数值二、完整使用步骤2.1 安装依赖ohpminstallpura/harmony-utils2.2 URL编码import{EncryptUtil}frompura/harmony-utils;Button(URL编码).width(100%).onClick((){try{letoriginalname张三age25;letencodedEncryptUtil.encodeURL(original);this.result原文:${original}\n编码:${encoded};}catch(e){this.result异常: e;}})2.3 URL解码Button(URL解码).width(100%).onClick((){try{letencodedname%E5%BC%A0%E4%B8%89age25;letdecodedEncryptUtil.decodeURL(encoded);this.result编码:${encoded}\n解码:${decoded};}catch(e){this.result异常: e;}})三、完整页面示例import{EncryptUtil}frompura/harmony-utils;EntryComponentstruct UrlEncodeDemo{Stateresult:string;build(){Column({space:12}){Button(URL编码).width(100%).onClick((){this.resultEncryptUtil.encodeURLComponent(name张三age25);});Button(URL解码).width(100%).onClick((){this.resultEncryptUtil.decodeURLComponent(name%E5%BC%A0%E4%B8%89);});Text(this.result).fontSize(14).fontColor(#333333)}.padding(16)}}四、进阶用法4.1 构建查询参数import{EncryptUtil}frompura/harmony-utils;functionbuildQueryString(params:Recordstring,string):string{returnObject.entries(params).map(([k,v])${EncryptUtil.encodeURLComponent(k)}${EncryptUtil.encodeURLComponent(v)}).join();}4.2 解析查询参数functionparseQueryString(query:string):Recordstring,string{letresult:Recordstring,string{};query.split().forEach(pair{let[k,v]pair.split();result[EncryptUtil.decodeURLComponent(k)]EncryptUtil.decodeURLComponent(v||);});returnresult;}五、注意事项双重编码避免对已编码的URL再次编码编码范围encodeURLComponent编码更多字符中文处理中文会被编码为%XX格式初始化依赖使用前需确保AppUtil.init()已调用空格处理URL中空格编码为%20或六、常见问题Q1: encodeURL和encodeURLComponent有什么区别encodeURL保留URL结构字符如:/?#encodeURLComponent编码所有特殊字符。Q2: 中文编码后是什么格式中文编码为UTF-8字节后再百分号编码如张编码为%E5%BC%A0。Q3: 解码失败会怎样安全解码会返回原始字符串或抛出可控异常。Q4: 空格编码为%20还是encodeURLComponent编码为%20表单提交通常使用。总结EncryptUtil的URL编解码方法为URL处理提供了便捷支持。本文详细介绍了核心API、使用步骤、完整示例、进阶用法以及常见问题的解决方案。开发者可以利用这些方法安全地构建和解析URL。本文基于pura/harmony-utils工具库更多功能请参考官方文档与后续系列文章。