java - 使用 java.net.URL 在 java 中构建不正确的 URL?

标签 java url java-8 construction

使用甲骨文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");

输出

http://localhost:4567/123/asd

关于java - 使用 java.net.URL 在 java 中构建不正确的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33349539/

相关文章:

java - 如何自动将所有相关类收集到一个jar中(使用maven)?

java - 编译我的第一个 java 应用程序时出现问题

php - 在 laravel 4 中生成相对于基本 url 的 url

jsf - 如何将 url 参数传递给 JSF/xHTML?

lambda - Java 8 中的 lambda 表达式如何支持函数式编程?

java - 如何修复编写代码检查 UPC 是否有效的 java 运行时错误?

java - Java中的字节递增操作

apache - 来自其他站点的错误 url ?fb_xd_fragment= redirect

java - Java 8 中的 java.util.logging.FileHandler 损坏了吗?

java - 手动链接 GroupBy 收集器