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

前言

URL编码(百分号编码)用于将特殊字符转换为%XX格式,确保URL中不包含非法字符。@pura/harmony-utils 的 EncryptUtil 封装了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 工具库,更多功能请参考官方文档与后续系列文章。

相关推荐
bufengwangluo16 小时前
动态代理IP是什么?从IP池到自动切换的工作机制解读
服务器·网络·ip
钉先生贾17 小时前
鸿蒙启动可靠性:把首屏依赖从“同时开始”改成可降级编排【鸿蒙心迹】
华为·php·harmonyos
bkspiderx17 小时前
C++符号冲突与内部符号优先策略详解
linux·服务器·c++·符号冲突·内部符号
tz52518 小时前
Superpowers 游戏开发实战应用场景大纲
linux·运维·服务器
如夏倾城1 天前
大模型(Large Model)解析:从数据类型、模型架构到任务选型
服务器·网络·数据库·语言模型·架构·audiolm
钉先生贾1 天前
HarmonyOS API 26 ArkUI 性能定位:用帧预算拆解页面卡顿【鸿蒙心迹】
华为·harmonyos
Kainy1 天前
生产服务器从机械盘迁移NVMe固态:旧盘不动、退路先行的六步实操全记录
运维·服务器
无足鸟ICT1 天前
【RHCA+】_proc_pid_attr_exec
linux·运维·服务器
普通人61 天前
uniapp鸿蒙开发完整指南
华为·uni-app·harmonyos
FlightYe2 天前
linux系统编程(二十一):C 语言常见坑
android·linux·运维·服务器·c语言·音视频