java.net.URL 和相对 url

发布于 2024-10-10 02:27:31 字数 475 浏览 2 评论 0原文

我的 URL 和相对路径(查询)有问题。我编写此代码是为了从相对 url 获取绝对 url:

    old = "http://domain/script?param";
    new_ = "?otherparam";
    URL u = new URL(old);
    u = new URL(u,new_);

这是输出:

JAVA URL: http://domain/script?param + ?otherparam = http://domain/?otherparam
FireFox: http://domain/script?param + ?otherparam = http://domain/script?otherparam

Why does URL's result different from FireFox?如何像 FireFox 一样构建 URL?

I have a problem with URL and relative path (query). I wrote this code to get absolute url from relative url:

    old = "http://domain/script?param";
    new_ = "?otherparam";
    URL u = new URL(old);
    u = new URL(u,new_);

Here is output:

JAVA URL: http://domain/script?param + ?otherparam = http://domain/?otherparam
FireFox: http://domain/script?param + ?otherparam = http://domain/script?otherparam

Why does URL's result differ from FireFox? How to build URL like FireFox does?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

残月升风 2024-10-17 02:27:31

Java 中的 BUG #6519518:当仅查询相对规范时,URL 错误地删除了路径叶 ( RFC1808)

描述包含解决方法。

It's BUG #6519518 in Java: URL incorrectly removes path leaf when the relative spec is query only (RFC1808)

The description contains a workaround.

半﹌身腐败 2024-10-17 02:27:31

阅读 URL(URL context, String spec) 的 javadoc 为您的问题提供了最佳答案:

如果规范的路径组件以斜杠字符“/”开头,则该路径将被视为绝对路径,并且规范路径将替换上下文路径。

否则,该路径将被视为相对路径并附加到上下文路径,如 RFC2396 中所述。此外,在本例中,通过删除因出现“..”和“.”而造成的目录更改,路径被规范化。

由于您的 URL 上下文 URL 结尾没有斜杠,因此它会被删除。

尝试添加斜杠:old = "http://domain/script/?param";

Reading javadoc of URL(URL context, String spec) provides the best answer to your question:

If the spec's path component begins with a slash character "/" then the path is treated as absolute and the spec path replaces the context path.

Otherwise, the path is treated as a relative path and is appended to the context path, as described in RFC2396. Also, in this case, the path is canonicalized through the removal of directory changes made by occurences of ".." and ".".

Since your URL context URL ends without slash, it's getting removed.

Try to add slash: old = "http://domain/script/?param";

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文