Constructing URL Objects

There are four constructors in the java.net.URL class. All can throw MalformedURLExceptions:

 public URL(String u) throws MalformedURLException
 public URL(String protocol, String host, String file) 
  throws MalformedURLException
 public URL(String protocol, String host, int port, String file) 
  throws MalformedURLException
 public URL(URL context, String u) throws MalformedURLException

Given a complete absolute URL like http://www.poly.edu/schedule/fall97/bgrad.html#cs, you construct a URL object for that URL like this:

 URL u = null;
  try {
    u = new URL("http://www.poly.edu/schedule/fall97/bgrad.html#cs");
  }
  catch (MalformedURLException ex) {
  
  }

You can also construct the URL by passing its pieces to the constructor, like this:

 URL u = null;
  try {
    u = new URL("http", "www.poly.edu", "/schedule/fall97/bgrad.html#cs");
  }
  catch (MalformedURLException ex) {
  
  }

You don't normally need to specify a port for a URL. Most protocols have default ports. For instance, the http port is 80; but sometimes this does change and in that case you can use the third constructor:

 URL u = null;
  try {
    u = new URL("http", "www.poly.edu", 80, "/schedule/fall97/bgrad.html#cs");
  }
  catch (MalformedURLException ex) {
  
  }

Finally, many HTML files contain relative URLs. For example, this page's URL is http://www.cafeaulait.org/course/week12/07.html. However, this entire site is mirrored in several places around the world. Rather than having to rewrite the internal links for each mirror site, relative URLs inherit the host, port, protocol, and possibly directory from the current page. Thus on this page a link to "08.html" refers to http://www.cafeaulait.org/course/week12/08.html. However when this same page is loaded from http://sunsite.lanet.lv/javafaq/course/week12/07.html, then the link to "08.html" refers to http://sunsite.lanet.lv/javafaq/course/week12/08.html instead.

The fourth constructor above creates URLs relative to a given URL. For example,

  try {
    URL u1 = new URL("http://www.cafeaulait.org/course/week12/07.html");
    URL u2 = new URL(u1, "08.html");
  }
  catch (MalformedURLException ex) {
  
  }

This is particularly useful when parsing HTML.


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998, 2003 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified May 6, 2003