我在期待

System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8"));

输出:

你好%20世界

(20是ASCII十六进制空格码)

然而,我得到的是:

你好+世界

我用错方法了吗?我应该使用的正确方法是什么?


当前回答

试试下面的方法:

添加一个新的依赖项

<!-- 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

其他回答

“+”是正确的。如果你真的需要%20,然后自己替换加。

警告:这个答案有很大的争议(+8 vs. -6),所以对这个答案持保留态度。

查看uri类。

URLEncoder使用字符集“ISO-8859-1”

我已经在使用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

我用错方法了吗?我应该使用的正确方法是什么?

是的,这个方法java.net.URLEncoder.encode并不是根据规范将“”转换为“20%”。

空格字符“”被转换为加号“+”。

即使这不是正确的方法,您也可以将其修改为:System.out.println(java.net.URLEncoder.encode(“Hello World”,“UTF-8”)。replaceAll("\\+", "%20"));祝你今天愉快=)。