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

时间:2019-07-11 12:15:49

标签: java

有什么方法可以从给定的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对象

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

只需使用URL构造函数即可构建新的URL。

URL newUrl = new URL(aURL.getProtocol(), aURL.getHost(), 8080, "/");