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

前言

URL编码(百分号编码)用于将特殊字符转换为%XX格式,确保URL中不包含非法字符。@pura/harmony-utilsEncryptUtil 封装了URL编解码方法。本文将从API说明、代码实战、进阶用法、常见问题等多个维度进行全面讲解,帮助开发者快速掌握并应用到实际项目中。

一、URL编解码核心API

EncryptUtil 提供了以下URL编解码方法:

方法 说明 返回类型 使用场景
encodeURL(str) URL编码 string URL编码
decodeURL(str) URL解码 string URL解码
encodeURLComponent(str) URL组件编码 string 参数编码
decodeURLComponent(str) URL组件解码 string 参数解码

1.1 核心特性

  • 简洁易用:封装复杂逻辑为一行调用,降低使用门槛
  • 类型安全:完整的TypeScript类型定义,编译期即可发现错误
  • 异常处理:内置异常捕获机制,避免运行时崩溃
  • 双重编码:支持URL整体编码和组件编码

1.2 encodeURL与encodeURLComponent对比

特性 encodeURL encodeURLComponent
编码范围 保留URL结构符 编码所有特殊字符
保留字符 😕?#\[\]@ 不保留
适用场景 完整URL 查询参数值

二、完整使用步骤

2.1 安装依赖

bash 复制代码
ohpm install @pura/harmony-utils

2.2 URL编码

typescript 复制代码
import { EncryptUtil } from '@pura/harmony-utils';

Button('URL编码')
  .width('100%')
  .onClick(() => {
    try {
      let original = 'name=张三&age=25';
      let encoded = EncryptUtil.encodeURL(original);
      this.result = `原文: ${original}\n编码: ${encoded}`;
    } catch (e) {
      this.result = '异常: ' + e;
    }
  })

2.3 URL解码

typescript 复制代码
Button('URL解码')
  .width('100%')
  .onClick(() => {
    try {
      let encoded = 'name=%E5%BC%A0%E4%B8%89&age=25';
      let decoded = EncryptUtil.decodeURL(encoded);
      this.result = `编码: ${encoded}\n解码: ${decoded}`;
    } catch (e) {
      this.result = '异常: ' + e;
    }
  })

三、完整页面示例

typescript 复制代码
import { EncryptUtil } from '@pura/harmony-utils';

@Entry
@Component
struct UrlEncodeDemo {
  @State result: string = '';

  build() {
    Column({ space: 12 }) {
      Button('URL编码').width('100%').onClick(() => {
        this.result = EncryptUtil.encodeURLComponent('name=张三&age=25');
      });
      Button('URL解码').width('100%').onClick(() => {
        this.result = EncryptUtil.decodeURLComponent('name=%E5%BC%A0%E4%B8%89');
      });
      Text(this.result).fontSize(14).fontColor('#333333')
    }
    .padding(16)
  }
}

四、进阶用法

4.1 构建查询参数

typescript 复制代码
import { EncryptUtil } from '@pura/harmony-utils';

function buildQueryString(params: Record<string, string>): string {
  return Object.entries(params)
    .map(([k, v]) => `${EncryptUtil.encodeURLComponent(k)}=${EncryptUtil.encodeURLComponent(v)}`)
    .join('&');
}

4.2 解析查询参数

typescript 复制代码
function parseQueryString(query: string): Record<string, string> {
  let result: Record<string, string> = {};
  query.split('&').forEach(pair => {
    let [k, v] = pair.split('=');
    result[EncryptUtil.decodeURLComponent(k)] = EncryptUtil.decodeURLComponent(v || '');
  });
  return result;
}

五、注意事项

  1. 双重编码:避免对已编码的URL再次编码
  2. 编码范围:encodeURLComponent编码更多字符
  3. 中文处理:中文会被编码为%XX格式
  4. 初始化依赖 :使用前需确保 AppUtil.init() 已调用
  5. 空格处理: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 工具库,更多功能请参考官方文档与后续系列文章。

相关推荐
千维百策6661 小时前
如何管理错误预算:提升服务可靠性与 SLO 达成率的实践经验
服务器·网络·数据库
图件制作GIS,储量计算2 小时前
未来已到,抓住机遇
运维·服务器
youtootech2 小时前
HarmonyOS 6.0 卡片式信息流与瀑布流布局
华为·harmonyos
学无止境_永不停歇2 小时前
9. 缓冲区
linux·服务器·c++
dok122 小时前
Johannes 《Linux内核模块与设备驱动开发:编写Linux驱动程序》(4) devicefile 设备号相关
linux·运维·服务器
毛驴赶鹿3 小时前
低配置服务器怎么搭建监控?Komari Docker部署与公网访问完整教程
运维·服务器·docker
Fu2067213 小时前
结课项目考试
linux·运维·服务器
Albert·Lin3 小时前
LVS相关知识点总结-一
linux·服务器·lvs
公众号:fuwuqiBMC4 小时前
(转自“服务器BMC”)服务器BMC芯片——AST1840
运维·服务器·fpga开发