鸿蒙三方库 | 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 工具库,更多功能请参考官方文档与后续系列文章。

相关推荐
SuperHeroWu78 小时前
HarmonyOS Dev Assistant (HarmonyOS开发助手)如何打通元服务开发全流程
ai·agent·harmonyos·vs code·元服务·hbuilderx·assistant
熊猫钓鱼>_>8 小时前
用 OHAudioSuite 空间渲染节点搭一座「3D 有声博物馆」——从三种模式到 FreeBuds 头追的实战记录
c++·3d·ai·harmonyos·arkts·audio·ohaudiosuite
新时代牛马8 小时前
Linux 驱动调试完整篇:从printk/dev_dbg、动态调试到 debugfs/ftrace 排障
java·linux·服务器
OH_TPC8 小时前
HarmonyOS APP开发---"心动卡"社交匹配App,需要用到这个库
harmonyos
光锥智能8 小时前
HUAWEI WATCH 6系列正式发布:鸿蒙AI手表,智慧健康旗舰
人工智能·华为·harmonyos
2603_965148119 小时前
宠物经济崛起:宠物食品用品API选品指南
大数据·服务器·人工智能·python·生活·宠物
Jae den9 小时前
什么是服务器虚拟化?
运维·服务器
光锥智能9 小时前
HUAWEI WATCH Ultimate 2 非凡探索推出滑雪登山功能,专业数据助力探索雪域奇境
华为
维克兜率天10 小时前
4.3.2.1 日常监控:上线只是开始
服务器·数据库·python·区块链·php·量化
zhengqweasd10 小时前
网站卡死、接口超时的隐性根源
运维·服务器·网络