查询字符串参数的 Java URL 编码

标签 java http url encoding urlencode

假设我有一个网址

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/

相关文章:

java - 如何为 Android 应用程序创建线程管理器?

http - 规范 URL 链接

http - Erlang:使用 Inets 的 HTTP GET 参数

Java URL - 传递参数 - Servlet

java - cfhttp 问题,因为它非常慢,尝试替代方案

Java:在对象类内部创建数组?

java - 确保收到 `response.getOutputStream().write()`

jsp - 可以使用JSTL c :if to test against a url pattern?

html - 为什么css中的背景图片表示为url,而img中的图片只能是文件路径

java - java 枚举的所有实例的模拟方法