假设我有一个网址
http://example.com/query?q=
我有一个用户输入的查询,例如:
random word £500 bank $
我希望结果是正确编码的 URL:
http://example.com/query?q=random%20word%20%A3500%20bank%20%24
实现这一目标的最佳方法是什么?我尝试了 URLEncoder
并创建了 URI/URL 对象,但没有一个是完全正确的。
最佳答案
URLEncoder
是要走的路。您只需要记住编码 only 单个查询字符串参数名称和/或值,而不是整个 URL,确保不是查询字符串参数分隔符 &
也不是参数名称-值分隔符 =
.
String q = "random word £500 bank $";
String url = "https://example.com?q=" + URLEncoder.encode(q, StandardCharsets.UTF_8);
当您仍未使用 Java 10 或更高版本时,请使用 StandardCharsets.UTF_8.toString()
作为字符集参数,或者当您仍未使用 Java 7 或更高版本时,请使用“UTF-8”
.
请注意,查询参数中的空格由 +
表示,而不是合法有效的 %20
。 %20
通常用于表示 URI 本身中的空格(URI 查询字符串分隔符 ?
之前的部分),而不是查询字符串中的空格(之后的部分?
).
另请注意,有三个 encode()
方法。一个没有 Charset
作为第二个参数,另一个使用 String
作为第二个参数,这会引发检查异常。不推荐使用没有 Charset
参数的那个。永远不要使用它并始终指定 Charset
参数。 javadoc甚至明确建议使用RFC3986 规定的UTF-8 编码。和 W3C .
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.
另见:
关于查询字符串参数的 Java URL 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10786042/