URL编解码
URL编码/解码,处理特殊字符和中文等非ASCII字符
处理参数
URL编码简介
URL编码是一种将URL中的特殊字符转换为可安全传输的格式的方法。它将非ASCII字符和特殊字符转换为%加上两位十六进制数的形式。
编码规则
- 保留字符(如字母、数字、-_.~)保持不变
- 特殊字符(如空格、&、=、?等)转换为%加上两位十六进制数
- 非ASCII字符(如中文)先转换为UTF-8编码,再转换为%加上两位十六进制数
常见用途
- URL参数传递
- 表单提交
- API请求
- 文件下载链接
代码示例
JavaScript:
// 编码
const str = 'https://example.com/path?name=测试&type=1';
const encoded = encodeURIComponent(str);
console.log(encoded);
// 解码
const decoded = decodeURIComponent(encoded);
console.log(decoded);
Python:
from urllib.parse import quote, unquote
# 编码
str = 'https://example.com/path?name=测试&type=1'
encoded = quote(str)
print(encoded)
# 解码
decoded = unquote(encoded)
print(decoded)
注意事项
- URL编码不是加密,仅用于字符转义
- 编码后的URL长度会增加
- 某些特殊字符可能需要多次编码