我在期待
System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8"));
输出:
你好%20世界
(20是ASCII十六进制空格码)
然而,我得到的是:
你好+世界
我用错方法了吗?我应该使用的正确方法是什么?
我在期待
System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8"));
输出:
你好%20世界
(20是ASCII十六进制空格码)
然而,我得到的是:
你好+世界
我用错方法了吗?我应该使用的正确方法是什么?
当前回答
该类执行application/x-www-form- urlenencoded -type编码,而不是百分比编码,因此替换为+是正确的行为。
从javadoc:
When encoding a String, the following rules apply: The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the same. The special characters ".", "-", "*", and "_" remain the same. The space character " " is converted into a plus sign "+". All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.
其他回答
Hello+World是浏览器为GET请求编码表单数据(application/x-www-form-urlencoded)的方式,这是URI查询部分的普遍接受的形式。
http://host/path/?message=Hello+World
如果将此请求发送到Java servlet, servlet将正确解码参数值。通常唯一出现问题的情况是编码不匹配。
严格来说,HTTP或URI规范中没有要求使用application/x-www-form- urlenencoded键-值对对查询部分进行编码;查询部分只需采用web服务器接受的形式即可。实际上,这不大可能成为一个问题。
对于URI的其他部分(例如路径)使用这种编码通常是不正确的。在这种情况下,您应该使用RFC 3986中描述的编码方案。
http://host/Hello%20World
更多的在这里。
这是预期的行为。URLEncoder实现了如何在HTML表单中编码url的HTML规范。
来自javadocs:
该类包含的静态方法 将String转换为 应用程序/ x-www-form-urlencoded MIME 格式。
和来自HTML规范:
应用程序/ x-www-form-urlencoded 使用此内容类型提交的表单 必须编码如下: 控件名称和值被转义。空格字符被替换 通过“+”
你必须更换它,例如:
System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8").replace("+", "%20"));
虽然很老了,但还是迅速回应:
Spring提供了UriUtils -使用它你可以指定如何编码以及它与URI的哪个部分相关。
encodePathSegment
encodePort
encodeFragment
encodeUriVariables
....
我使用它们是因为我们已经在使用Spring,即不需要额外的库!
“+”是正确的。如果你真的需要%20,然后自己替换加。
警告:这个答案有很大的争议(+8 vs. -6),所以对这个答案持保留态度。
试试下面的方法:
添加一个新的依赖项
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>10.0.13</version>
</dependency>
现在按照下面的步骤做:
String str = "Hello+World"; // For "Hello World", decoder is not required
// import java.net.URLDecoder;
String newURL = URLDecoder.decode(str, StandardCharsets.UTF_8);
// import org.apache.catalina.util.URLEncoder;
System.out.println(URLEncoder.DEFAULT.encode(newURL, StandardCharsets.UTF_8));
你会得到如下的输出:
Hello%20World