有没有办法从给定的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
有什么想法吗?
我找到了较短的方法,可以保留除路径部分以外的所有内容,请使用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/"
只需使用 URL
构造函数来构建一个新的 URL。
URL newUrl = new URL(aURL.getProtocol(), aURL.getHost(), 8080, "/");