URL编码/解码工具

关于URL编码/解码

URL是什么

URL(统一资源定位符)是用于定位互联网资源的字符串,由协议、域名、路径等组成。由于URL只能包含ASCII字符集,特殊字符和非ASCII字符必须进行编码处理。

什么是URL编码

URL编码(百分比编码)是将特殊字符转换为%后跟两位十六进制数的格式。这是为了在URL中安全传输数据,避免特殊字符引起歧义。例如,空格会被编码为%20或+号。

Python实现URL编码和解码

      
from urllib.parse import quote, unquote

# Encoding
encoded = quote("hello world!@", safe="")
print(encoded)  # hello%20world%21%40

# Decoding
decoded = unquote("hello%20world%21%40")
print(decoded)  # hello world!@
      
    

JavaScript实现URL编码和解码

      
// Encoding
const encoded = encodeURIComponent('hello world!@');
console.log(encoded); // hello%20world%21%40

// Decoding
const decoded = decodeURIComponent('hello%20world%21%40');
console.log(decoded); // hello world!@
      
    

Java实现URL编码和解码

      
import java.net.URLEncoder;
import java.net.URLDecoder;

// Encoding
String encoded = URLEncoder.encode("hello world!@", "UTF-8");
System.out.println(encoded); // hello+world%21%40

// Decoding
String decoded = URLDecoder.decode("hello+world%21%40", "UTF-8");
System.out.println(decoded); // hello world!@
      
    

URL编码的使用场景

  • 在URL参数中传递特殊字符
  • 表单数据提交时的内容编码
  • API请求中的参数安全传输
  • 处理非ASCII字符(如中文)的编码需求

URL编码注意事项

  • 编码会转换所有非安全字符(包括字母数字和-_.~)
  • 解码时遇到无效编码会显示错误提示
  • 空格在编码后可能显示为%20或+号,需注意应用场景
  • 编码后的字符串长度会增加,请注意长度限制