有沒有辦法從給定的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 = httpauthority = example.com:80host = example.comport = 80path = /docs/books/tutorial/index.htmlquery = name=networkingfilename = /docs/books/tutorial/index.html?name=networkingref = DOWNLOADING我想得到的是一個新URL對象http://example.com:8080有任何想法嗎?
2 回答

翻閱古今
TA貢獻1780條經驗 獲得超5個贊
我找到了更短的方法來維護除路徑部分以外的所有內容,使用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/"

子衿沉夜
TA貢獻1828條經驗 獲得超3個贊
只需使用URL
構造函數來構建一個新的 URL。
URL newUrl = new URL(aURL.getProtocol(), aURL.getHost(), 8080, "/");
添加回答
舉報
0/150
提交
取消