Sten Kin
Sten Kin

Reputation: 2615

Remove parameters from a URL regardless

Let's say we have a URL like the following:

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

I like to just get https://www.google.com/search. There are a few easy ways to do this like so String baseUrl = url.split("?")[0]; What's a better/safe way to do this? Is there something build in?

Upvotes: 0

Views: 120

Answers (2)

Julian Reschke
Julian Reschke

Reputation: 42045

RFC 3986 (the specification for URIs) contains a regexp you can use: http://greenbytes.de/tech/webdav/rfc3986.html#regexp

Upvotes: 2

ederollora
ederollora

Reputation: 1181

You could use URL type, and it's methods.

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();
    }
} 

Output:

protocol is https

host is www.google.com

path is /search

https://www.google.com/search

Upvotes: 3

Related Questions