org.springframework.web.util.UriUtils.encode 和 java.net.URLEncoder.encode 的结果通常 不完全一致,因为它们的用途和编码范围存在差异。
1. UriUtils.encode (Spring)
- 用途: 用于对 URI(Uniform Resource Identifier)中的不同部分(如路径、查询参数等)进行编码。
- 特点:
- 遵循 RFC 3986 标准,这是一种更现代的 URI 编码规则。
- 保留 URI 中的特殊字符,如
/、?、&等,它们在 URI 中有特定含义,不会被编码。
2. URLEncoder.encode (Java)
- 用途: 用于将表单数据或查询字符串中的参数值编码。
- 特点:
- 遵循 application/x-www-form-urlencoded 规范。
- 会将所有非字母数字字符(包括
/、?等)编码。 - 替换空格为加号(
+),而不是%20。
示例对比
假设 url = "https://example.com/path?query=value&other=value":
-
Spring 的
UriUtils.encode:String encoded = UriUtils.encode(url, StandardCharsets.UTF_8); System.out.println(encoded);输出(仅编码非保留字符):
https://example.com/path?query=value&other=value -
Java 的
URLEncoder.encode:String encoded = URLEncoder.encode(url, StandardCharsets.UTF_8); System.out.println(encoded);输出(全面编码):
https%3A%2F%2Fexample.com%2Fpath%3Fquery%3Dvalue%26other%3Dvalue
结论
- 如果目标是对 整个 URL 进行编码(包括特殊字符),使用
URLEncoder.encode更合适。 - 如果目标是对 URI 的一部分(如路径、查询参数值)进行编码,同时保留 URI 的语义(如
/、&等),使用UriUtils.encode更合适。
在实际开发中,应根据具体场景选择合适的方法。
8444

被折叠的 条评论
为什么被折叠?



