为什么网址会出现乱码?URL 编码原理

一、URL 编码的必要性

URL 只能包含 ASCII 字符集中的一部分字符。当 URL 中包含中文、空格或特殊符号时,必须进行编码转换,否则会导致 URL 解析错误或出现乱码。

二、URL 编码原理

URL 编码(也称为百分号编码)将不安全或特殊的字符转换为 %xx 格式,其中 xx 是字符的 ASCII 码的十六进制表示。例如:

  • 空格 → %20
  • 中文"中" → %E4%B8%AD
  • & → %26
  • = → %3D

三、中文、特殊符号编码场景

  • URL 参数传递:URL 查询参数中包含中文或特殊字符
  • 表单提交:GET 请求的表单数据
  • 文件路径:URL 中包含特殊字符的文件名
  • API 接口:RESTful API 的路径参数

四、接口请求中 URL 转义常见问题

  • 双重编码:前端和后端都进行编码导致错误
  • 编码不一致:不同语言的编码方式差异
  • 特殊字符遗漏:某些特殊字符未被正确编码
  • 空格处理:空格有时编码为 %20,有时为 +

五、解决方案

  • 统一编码方式(推荐使用 encodeURIComponent)
  • 明确前后端的编码职责
  • 使用在线工具验证编码结果
  • 对敏感字符进行双重检查
🔧 使用 URL 编码解码工具

Why URLs Show Garbled Text? URL Encoding Explained

I. The Need for URL Encoding

URLs can only contain a subset of ASCII characters. When URLs contain Chinese characters, spaces, or special symbols, they must be encoded to prevent parsing errors or garbled text.

II. URL Encoding Principle

URL encoding (also called percent-encoding) converts unsafe or special characters into %xx format, where xx is the hexadecimal ASCII value of the character. For example:

  • Space → %20
  • Chinese "中" → %E4%B8%AD
  • & → %26
  • = → %3D

III. Chinese & Special Character Encoding Scenarios

  • URL Parameters: URL query parameters containing Chinese or special characters
  • Form Submission: GET request form data
  • File Paths: Filenames with special characters in URLs
  • API Endpoints: RESTful API path parameters

IV. Common URL Escaping Issues in API Requests

  • Double Encoding: Both frontend and backend encode, causing errors
  • Encoding Inconsistency: Different encoding methods across languages
  • Missing Special Characters: Some special characters not properly encoded
  • Space Handling: Spaces sometimes encoded as %20, sometimes as +

V. Solutions

  • Use consistent encoding method (prefer encodeURIComponent)
  • Clarify encoding responsibilities between frontend and backend
  • Validate encoding results with online tools
  • Double-check sensitive characters
🔧 Use URL Encoder/Decoder Tool