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

标签 java http url netty

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

相关文章:

java - 删除 Java 二叉搜索树中的方法

javascript - 使用 javascript 发送 HTTP 请求和接收 HTTP 响应

python - 运行代码时我不断收到 "list indices must be integers or slices, not str"错误

javascript - 单击另一个页面上的按钮 - HTML

java - 无法在 Windows 10 上安装 Java(1603 错误)

java - 在这种情况下如何在drools中使用collect()

java - Java中负数转0的基本问题

python - 如何使用 Python 通过 HTTP 发送文件?

http - 在 https 上运行的生产服务器中,但在实时(在 Internet 上)中它仅显示 http

ios - 如何将 NSUserdefault 的值放入 URL