我在期待

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

输出:

你好%20世界

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

然而,我得到的是:

你好+世界

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


当前回答

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

其他回答

这是预期的行为。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"));

一个空格在url中被编码为%20,在表单提交的数据中被编码为+(内容类型为application/x-www-form-urlencoded)。你需要前者。

使用番石榴:

dependencies {
     compile 'com.google.guava:guava:23.0'
     // or, for Android:
     compile 'com.google.guava:guava:23.0-android'
}

你可以使用UrlEscapers:

String encodedString = UrlEscapers.urlFragmentEscaper().escape(inputString);

不要使用String。替换,这只会编码空间。使用库代替。

查看uri类。

查询参数

org.apache.commons.httpclient.util.URIUtil
    URIUtil.encodeQuery(input);

如果你想转义URI中的字符

public static String escapeURIPathParam(String input) {
  StringBuilder resultStr = new StringBuilder();
  for (char ch : input.toCharArray()) {
   if (isUnsafe(ch)) {
    resultStr.append('%');
    resultStr.append(toHex(ch / 16));
    resultStr.append(toHex(ch % 16));
   } else{
    resultStr.append(ch);
   }
  }
  return resultStr.toString();
 }

 private static char toHex(int ch) {
  return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
 }

 private static boolean isUnsafe(char ch) {
  if (ch > 128 || ch < 0)
   return true;
  return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
 }

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