gpt4 book ai didi

java - 无论如何从 URL 中删除参数

转载 作者:行者123 更新时间:2023-12-01 17:14:53 30 4
gpt4 key购买 nike

假设我们有一个如下所示的 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

https://www.google.com/search

关于java - 无论如何从 URL 中删除参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22672319/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com