2014-03-26 58 views
0

比方說,我們有類似下面的網址:從URL刪除參數無論

https://www.google.com/search?q=X&b=Y 

我喜歡只得到https://www.google.com/search。有幾個簡單的方法可以做到這一點,如 String baseUrl = url.split("?")[0];什麼是更好/安全的方式來做到這一點?有內置的東西嗎?

+0

是這種分裂方式,一種不安全的方式嗎?對我來說這已經足夠了 – ederollora

+0

當用戶插入網址時,問題可能會開始 –

+0

然後檢查長度,檢查點,檢查'?'符號。然後問題不在於提取URL部分,而是因爲split方法需要一個正則表達式,用戶可能無法輸入 – ederollora

回答

3

你可以使用URL類型,它是方法。

public static void main(String [] args){ 
    try 
    { 
     URL url = new URL("https://www.google.com/search?q=X&b=Y"); 


     System.out.println("protocol is " + url.getProtocol()); 
     // |-> prints: 'https' 
     System.out.println("hot is "+ url.getHost()); 
     // url.getAuthority() is valid too, but may include the port 
     // incase it's included in the URL 
     // |-> prints: 'www.google.com' 
     System.out.println("path is " + url.getPath()); 
     // |-> prints: '/search' 

     //WHat you asked for   
     System.out.println(url.getProtocol()+"://"+ url.getAuthority()+url.getPath()); 
     // |-> prints: 'https://www.google.com/search' 
    }catch(IOException e){ 
     e.printStackTrace(); 
    } 
} 

輸出:

協議是HTTPS

宿主是www.google.com

路徑是/搜索

https://www.google.com/search

+1

如果URL包含端口,該怎麼辦?如果它包含ref? – Steinar

+0

這是一個很好的問題,但是我的回答嚴格涵蓋了這個人所要求的。但是,回答你的問題,如果url有一個端口,它也應該工作,但必須使用getHost(),而不是getAuthority()。沒有試過參考 – ederollora

+0

你能寫一個可以應用於'ref'情況的URL例子嗎?就像我知道的那樣,也有一個getRef()方法。 – ederollora