java.net.URL 构建 URL 时有错误?

java.net.URL bug in constructing URLs?

结构 new URL(new URL(new URL("http://localhost:4567"), "abc"), "def") 产生(错误地恕我直言)这个 url:http://localhost:4567/def

虽然构造 new URL(new URL(new URL("http://localhost:4567"), "abc/"), "def") 产生了正确的(我想要的)url:http://localhost:4567/abc/def

不同之处在于 abc 构造函数参数中的尾部斜杠。

这是预期的行为还是应该在 URL class 中修复的错误?
毕竟,当你使用一些助手 class 进行 URL 构造时,不要担心斜杠。

引用 new URL(URL context, String spec) 的 javadoc:

Otherwise, the path is treated as a relative path and is appended to the context path, as described in RFC2396.

请参阅 RFC2396 规范的第 5 "Relative URI References" 节,特别是第 5.2 节 "Resolving Relative References to Absolute Form",第 6a 项:

All but the last segment of the base URI's path component is copied to the buffer. In other words, any characters after the last (right-most) slash character, if any, are excluded.

说明

在网页上,"Base URI"是页面地址,例如http://example.com/path/to/page.html。亲戚 link,例如<a href="page2.html">,必须解释为基础 URI 的 兄弟 ,因此删除 page.html,并添加 page2.html,导致 http://example.com/path/to/page2.html,如预期。

JavaURLclass实现了这个逻辑,这就是为什么你得到你所看到的,这完全是它应该工作的方式。

这是设计使然,即不是错误。