URL 编解码完全指南:百分号编码的原理与实战

加密编码(更新于 2026年5月27日)

URL 结构回顾

https://user:pass@www.example.com:8080/path/to/page?name=张三&age=25#section
└──┬──┘ └────┬────┘ └──────┬──────┘└─┬─┘└────┬─────┘└──────┬──────┘└──┬──┘
  scheme   userinfo     host      port    path        query     fragment

只有 path、query、fragment 部分需要编码。scheme 和 host 有各自的规则。


为什么需要 URL 编码?

URL 只能包含 ASCII 可打印字符。以下字符必须编码:

字符 编码 原因
空格 %20+ 不允许裸空格
中文「张三」 %E5%BC%A0%E4%B8%89 非 ASCII
& %26 query 分隔符
= %3D key=value 分隔符
# %23 fragment 标识
? %3F query 开始
/ %2F path 分隔符

使用工具库 URL 编解码

操作步骤

  1. 打开 URL 编解码工具
  2. 输入 URL 或文本
  3. 选择 encode 或 decode
  4. 查看结果

encodeURI vs encodeURIComponent

函数 不编码 适用
encodeURI() : / ? # [ ] @ ! $ & ' ( ) * + , ; = 完整 URL
encodeURIComponent() A-Z a-z 0-9 - _ . ! ~ * ' ( ) URL 参数值
const base = 'https://example.com/search';

// ✅ 编码参数值
const url = `${base}?q=${encodeURIComponent('hello world')}`;
// → https://example.com/search?q=hello%20world

// ❌ 编码整个 URL
const wrong = encodeURIComponent('https://example.com/search?q=test');
// → https%3A%2F%2Fexample.com%2Fsearch%3Fq%3Dtest

实战场景

中文 query 参数

原始: https://search.com/q=前端开发
编码: https://search.com/q=%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91

解析 URL 参数

使用 URL 解析工具 分解 URL 并展示 query 参数表:

输入: https://api.com/users?name=张三&role=admin&page=1
输出:
  name  = 张三
  role  = admin
  page  = 1

国际化域名 (IDN)

中文域名「工具库.com」的 Punycode 编码:

工具库.com → xn--6qq986b3xl.com

使用 Punycode 工具 互转。

Base64 编码 URL 参数

有时需要将 JSON 对象编码为 URL 参数:

{"user":"admin","role":"editor"}
  → Base64 → eyJ1c2VyIjoiYWRtaW4iLCJyb2xlIjoiZWRpdG9yIn0=
  → URL encode → eyJ1c2VyIjoiYWRtaW4iLCJyb2xlIjoiZWRpdG9yIn0%3D

常见错误

双重编码

原始: hello world
一次编码: hello%20world  ✅
两次编码: hello%2520world  ❌ (解码一次得到 hello%20world)

编码整个 URL

只对参数值使用 encodeURIComponent,不要对完整 URL 编码。

空格用 + 还是 %20

  • Query 参数中:+%20 等价
  • Path 中:只能用 %20
  • 建议统一使用 %20

总结

URL 编码是 Web 开发的基本功。理解 encodeURI 与 encodeURIComponent 的区别、中文参数的 UTF-8 编码、以及国际化域名的 Punycode 转换,能避免大量调试时间。工具库提供 URL 编解码URL 解析Punycode 工具。

#URL#编解码#百分号编码#查询参数#Web