使用甲骨文java 1.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");
输出
关于java - 使用 java.net.URL 在 java 中构建不正确的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33349539/