假设我们有一个如下所示的 URL:
https://www.google.com/search?q=X&b=Y
我喜欢直接获取 https://www.google.com/search
。有一些简单的方法可以做到这一点,就像这样
String baseUrl = url.split("?")[0];
有什么更好/安全的方法来做到这一点?有内置的东西吗?
最佳答案
您可以使用 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();
}
}
输出:
protocol is https
host is www.google.com
path is /search
关于java - 无论如何从 URL 中删除参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22672319/