URLDecoder 正在将“+”转换为 space

URLDecoder is converting '+' into space

我的一个查询参数中有一个散列键,它可以包含 + char 和其他特殊字符。问题是当 URL 被解码时 URL 解码器将 + char 转换为 space。 有没有一种方法可以强制 URL 解码器不将 '+' 转换为 space.

在解码之前对字符串执行此操作:

String plusEncoded = yourString.replaceAll("\+", "%2b")

解码器随后会+显示它应该在的位置

根据HTML URL Encoding Reference

URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

+ 符号本身必须用 %2B 编码。因此,如果您想在 URL 中将哈希作为 GET 参数传递,则应在哈希 中将加号替换为 %2B 。不要替换整个 URL 中的每个 +,因为您可能会破坏其他假定包含空格的字符串参数。

有一个与此问题类似的错误参考,已关闭为“不是问题”。在这里我引用受让人所说的话:

The Java API documentation at https://docs.oracle.com/javase/8/docs/api/java/net/URL.html clearly states that "The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which is not the same as the encoding scheme defined in RFC2396." . This means that it is not meant for URL encoding and will cause issues with spaces and plus signs in the path. Using URL or URI classes to construct the url will give expected results.

URL url = new URL(input);
System.out.println(url.toString()); //outputs http://www.example.com/some+thing

参考: https://bugs.openjdk.java.net/browse/JDK-8179507