How can I parse a URL?

Brandon Rohlfs

The URL class contains a variety of accessor methods, which return the values of a URL's components. URL's use of accesors makes having to parse a URL to gain this information a thing of the past. The following is an abbreviated list of the accesor methods that the URL class provides.

  • public String getProtocol()
  • public String getHost()
  • public int getPort()
  • public String getFile()
  • public String getQuery()
  • public String getRef()

Depending on what a URL is made up of, some of the accessor methods will return null or an empty String. For instance the in following code getQuery() and getRef() return null since our URL lacks both.

import java.net.URL; 
import java.net.MalformedURLException; 

public class URLParser{
 public static void main(String[] args){
  URL url = null; 
  try{
  url = new URL("http://java.sun.com/jugs/pointers.html");
  }catch(MalformedURLException me){
   System.out.println(me); 
  }
  System.out.println("Protocol: " + url.getProtocol());
  System.out.println("Host: " + url.getHost()); // if no host specified, empty String returned
  System.out.println("Port: " + url.getPort()); // if no port specified -1 returned 
  System.out.println("Port: " + url.getDefaultPort()); // returns the default port 80
  
  System.out.println("File: " + url.getFile()); // if no file specified, empty String returned 
  System.out.println("Query : " + url.getQuery()); //no query string? null returned
  System.out.println("Ref: " + url.getRef()); // no ref? null returned 
 }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact