使用 java.net.URL 在 java 中构造错误的 URL?
Construct incorrect URLs in java with java.net.URL?
使用甲骨文java1.8.0_25
我有以下结构
URL url = new URL(new URL(new URL("http://localhost:4567/"), "123"), "asd")
根据 https://docs.oracle.com/javase/tutorial/networking/urls/creatingUrls.html
中的文档
它应该产生 http://localhost:4567/123/asd
的 URL
但它会产生 http://localhost:4567/asd
文档说明
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.
这是正确的行为吗?
阅读使用此构造函数的文档后:
URL(URL baseURL, String relativeURL)
所以你可以这样做:
URL baseUrl = new URL("http://localhost:4567/");
URL url = new URL(baseUrl, "123/asd")
或者您可以单行执行此操作:
URL url = new URL(new URL(new URL("http://localhost:4567/"), "123/"), "asd");
输出
使用甲骨文java1.8.0_25
我有以下结构
URL url = new URL(new URL(new URL("http://localhost:4567/"), "123"), "asd")
根据 https://docs.oracle.com/javase/tutorial/networking/urls/creatingUrls.html
中的文档
它应该产生 http://localhost:4567/123/asd
的 URL
但它会产生 http://localhost:4567/asd
文档说明
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.
这是正确的行为吗?
阅读使用此构造函数的文档后:
URL(URL baseURL, String relativeURL)
所以你可以这样做:
URL baseUrl = new URL("http://localhost:4567/");
URL url = new URL(baseUrl, "123/asd")
或者您可以单行执行此操作:
URL url = new URL(new URL(new URL("http://localhost:4567/"), "123/"), "asd");