javaurljava-8construction

Construct incorrect URLs in java with java.net.URL?


Using oracle java 1.8.0_25

I have the following construct

URL url = new URL(new URL(new URL("http://localhost:4567/"), "123"), "asd")

According the documentation in https://docs.oracle.com/javase/tutorial/networking/urls/creatingUrls.html
it should produce the URL of http://localhost:4567/123/asd
But it produces http://localhost:4567/asd

The documentation states

This code snippet uses the URL constructor that lets you create a URL object from another URL object (the base) and a relative URL specification. The general form of this constructor is:

URL(URL baseURL, String relativeURL)
The first argument is a URL object that specifies the base of the new URL. The second argument is a String that specifies the rest of the resource name relative to the base. If baseURL is null, then this constructor treats relativeURL like an absolute URL specification. Conversely, if relativeURL is an absolute URL specification, then the constructor ignores baseURL.

Is this the correct behavior here?


Solution

  • After reading the documentation using this constructor:

    URL(URL baseURL, String relativeURL)
    

    So you can do something like this:

    URL baseUrl = new URL("http://localhost:4567/");
    URL url = new URL(baseUrl, "123/asd")
    

    Or you can do this as a one-liner:

    URL url = new URL(new URL(new URL("http://localhost:4567/"), "123/"), "asd");
    

    Output

    http://localhost:4567/123/asd