我们假设我们有以下网址:
https://www.google.com/search?q=X&b=Y
我想得到https://www.google.com/search
。有一些简单的方法可以做到这一点
String baseUrl = url.split("?")[0];
更好/更安全的方法是什么?是否有东西内置?
答案 0 :(得分:3)
您可以使用网址类型及其方法。
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
路径是/ search
答案 1 :(得分:2)
RFC 3986(URI规范)包含一个可以使用的正则表达式:http://greenbytes.de/tech/webdav/rfc3986.html#regexp