简体   繁体   中英

java.net.URL and relative 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?

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

The description contains a workaround.

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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