我在期待
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十六进制空格码)
然而,我得到的是:
你好+世界
我用错方法了吗?我应该使用的正确方法是什么?
当前回答
它不是一行代码,但是你可以使用:
URL url = new URL("https://some-host.net/dav/files/selling_Rosetta Stone Case Study.png.aes");
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
System.out.println(uri.toString());
这将给你一个输出:
https://some-host.net/dav/files/selling_Rosetta%20Stone%20Case%20Study.png.aes
其他回答
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使用字符集“ISO-8859-1”
查看uri类。
其他答案要么提供手动字符串替换,实际上编码HTML格式的URLEncoder, Apache放弃的URIUtil,或者使用Guava的UrlEscapers。最后一个很好,除了它没有提供解码器。
Apache Commons Lang提供了URLCodec,它根据URL格式rfc3986进行编码和解码。
String encoded = new URLCodec().encode(str);
String decoded = new URLCodec().decode(str);
如果您已经在使用Spring,您也可以选择使用它的UriUtils类。
我已经在使用Feign了,所以我可以使用UriUtils,但Spring UrlUtils不行。
<!-- https://mvnrepository.com/artifact/io.github.openfeign/feign-core -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>11.8</version>
</dependency>
我的模拟测试代码:
import feign.template.UriUtils;
System.out.println(UriUtils.encode("Hello World"));
输出:
你好%20世界
正如该类所暗示的,它编码uri而不是url,但OP要求的是uri而不是url。
System.out.println(UriUtils.encode("https://some-host.net/dav/files/selling_Rosetta Stone Case Study.png.aes"));
输出:
2F https 3A % % 2Fsome-host。网2Fdav % 2Ffiles 2Fselling_Rosetta % 20Stone 20Case % 20Study png。aes