Constructing URLs
Java expresses URLs using the URL class. The URL class allows the program to take a simple text string, such as http://www.httprecipes.com/
, and transform it into a URL object that Java can deal with. The following code segment demonstrates this.
try
{
URL u = new URL("http://www.httprecipes.com/");
} catch (MalformedURLException e)
{
e.printStackTrace();
}As you can see, a URL object can be constructed simply by passing a String, containing the desired URL, to the constructor of the URL class. You should also notice that a catch block is required. This is because the MalformedURLException exception can be thrown. The MalformedURLException will be thrown if an invalid URL is provided.
For example, the following would throw the MalformedURLException.
try
{
URL u = new URL("http;//www.httprecipes.com/");
} catch (MalformedURLException e)
{
e.printStackTrace();
}The MalformedURLException would be thrown because the "http" protocol specified ends with a semicolon instead of a colon.




