2

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?

2
  • 1
    According to the documentation: URL url = new URL("http", "localhost", 4567, "123/asd") ? Commented Oct 26, 2015 at 15:33
  • 2
    Question is edited with the addition of quoted text from docs. There are examples also. Commented Oct 26, 2015 at 15:38

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

4 Comments

I edited my answer. You were missing / after 123.
I mean without trailing slashes anywhere. After all that it the idea not to worry about slashes when construct the URLs.
@George Yeah I got what you say. It's weird it doesn't work like that.
@George: I suppose, if the base URL was http://host/path/index.html, everyone would agree that resolving the relative URL about.html against it, should result in http://host/path/about.html rather than http://host/path/index.html/about.html. Since the rules do not care about whether the name is index.html vs path or 123 vs asd, what makes the difference? → the trailing slash (or the absence of it)…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.