Java - new URL(...) 不转义第一个字符

Java - new URL(...) doesn't escape the first character

我正在尝试创建一个 link 来打开 Github 上的 New issue 页面,并在其中填充现有的问题知识。

为此,我使用如下查询参数:

https://github.com/User/Repository/issues/new?title=Some text&body=More Text

效果很好,但是我正在尝试使用 Markdown 格式化文档,并且在通过调用

创建新的 URL 后所有符号都被转义
URL url = new URL("https://github.com/User/Repository/issues/new?title=Some text&body=# Header # Another header");

结果将是这样的:

https://github.com/User/Repository/issues/new?title=Some text&body=# Header %23 Another header

第二个 # 正在转义,但第一个不是,我不太明白为什么。

有什么想法吗?

简而言之,URL 解析器将您的第一个 # 视为一个片段(a.k.a。anchor, e.g. <a name="named-anchor">). Since according to RFC-3986: Section 3,该片段必须排在最后并且 # 是一个保留字符,第一个 # 之后的任何内容都被假定为该片段的一部分,从而导致解析器对任何进一步的“无效”字符进行编码,例如您的第二个 #。来自 RFC:

The generic URI syntax consists of a hierarchical sequence of components referred to as the scheme, authority, path, query, and fragment.

URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]

请注意,fragment 排在最后,由 # 分隔。

处理此问题的最佳方法是:

  1. encode the body query parameter 自己或
  2. 使用为您进行转义的 HTTP 客户端,例如RestTemplate from Spring or Apache HttpComponents.