简体   繁体   English

java.net.URL和相对URL

[英]java.net.URL and relative url

I have a problem with URL and relative path (query). URL和相对路径(查询)有问题。 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? 为什么URL的结果与FireFox不同? How to build URL like FireFox does? 如何像FireFox一样构建URL?

It's BUG #6519518 in Java: URL incorrectly removes path leaf when the relative spec is query only (RFC1808) 它是Java中的BUG#6519518: 当相对规范仅用于查询时,URL错误地删除了路径叶(RFC1808)

The description contains a workaround. 该描述包含解决方法。

Reading javadoc of URL(URL context, String spec) provides the best answer to your question: 读取URL的 javadoc (URL上下文,字符串规范)可为您的问题提供最佳答案:

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. 否则,如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"; 尝试添加斜杠: old = "http://domain/script/?param";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM