Java URL: 获取URL对象的根路径(删除路径)

8

是否有办法从给定的URL中仅获取方案+主机+端口。

也就是说,我想删除路径 URL 段。

URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                       + "/index.html?name=networking#DOWNLOADING");

我一直在尝试使用这个工具:

System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());

输出结果是:

protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING

我想要的是一个新的URL对象,它指向http://example.com:8080。 有什么建议吗?
2个回答

4
我找到了一个更短的方法,它保留了所有内容,但省略了路径部分,可以使用URI.resolve()
URL url = new URL("http://example.com:8081/api/test");
System.out.println(url)// prints "http://example.com:8081/api/test"

URL urlNoPath = url.resolve("/");
System.out.println(url)// prints "http://example.com:8081/"

你是在从 java.net.URL 进行导入吗?我遇到了符号解析未找到的问题。在 Oracle 文档中也没有找到这个方法。 - undefined

2
只需使用URL构造函数来创建新的URL。最初的回答。
URL newUrl = new URL(aURL.getProtocol(), aURL.getHost(), 8080, "/");

我认为OP正在寻找一个单一的URL方法,可以在不必显式指定主机、端口和斜杠的情况下完成该操作。 - Amnon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接