亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java URL:獲取 URL 對象的根(刪除路徑)

Java URL:獲取 URL 對象的根(刪除路徑)

狐的傳說 2023-03-17 16:37:31
有沒有辦法從給定的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/"


查看完整回答
反對 回復 2023-03-17
?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

只需使用URL構造函數來構建一個新的 URL。

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


查看完整回答
反對 回復 2023-03-17
  • 2 回答
  • 0 關注
  • 210 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號