What is a URL and how can I construct one?

Brandon Rohlfs

A URL (Uniform Resource Locator) represents a reference to resource on a network. The resource may take many forms. Maybe it is an image stored on a web server of that sports car youve been dreaming about buying or a database query of your favorite cooking books or maybe even a trailer for that cool new kung foo flick coming out.

Ok so what does a URL look like? URL's are basically broken down into two parts, the protocol and the resource name. The protocol is separated from the resource name by a colon and two forward slashes ://. The protocol simply defines the rules of exchange. In the case of the http protocol, the set of rules applies to how the connection to the server (where the resourse resides) is established, how the client request is made and how the response from the server is made and also the forms of the request/response. There are also many other different protocols like FTP (File Transfer Protocol) but we are only concerned with the the http (HyperText Transfer Protocol). The resource name is the complete address to the resource and normally consists of the host name, port number and file name with the port number usually being optional.

So how is a URL constructed? Java provides the URL class which is used to represent a resource on a network. This class resides within the java.net namespace. The URL class provides multiple constructors with the easiest one to remember being URL(String spec). For instance we can use this constructor to create a new URL object.

URL ir = new URL("http://www.importracing.com/");

The URL created above is commonly referred to as an Absolute URL. What this means is that all of the information provided is enough to reach the particular resource.

A URL can also be created from parts such as the protocol, host, and filename.

URL ir = new URL("http", "www.importracing.com", "/hondacivicimages/civicsi.jpeg");

URL's can also be created which are relative to another URL (it's base). For instance say we have an html page with various images. We can create a URL to be used as the base. Then create a new URL object relative to that base.

URL ir = new URL("http://www.importracing.com"); // base URL  
URL civicimages = new URL(ir, "/hondacivicimages.html") // relative to it's base
URL accordimages = new URL(ir, "/hondaaccordimages.html") // relative to it's base

Lastly, when a URL is created we must take into account that the url might be incorrect such as using an illegal protocol. In oder to deal with this all that is needed is to wrap the line that creates the instance of the URL within a try{ }catch(MalformedURLException me) block like in the following example.

 URL ir = new URL("http://www.importracing.com");
}catch(MalformedURLException me){
 // exception handling code