Java Reference
In-Depth Information
This will create a new
URL
object that is ready to be used. However, it can throw a
checked exception, named
MalformedURLException
. As mentioned previously, to
properly handle the exception you should use the following code.
try
{
URL url = new URL("http://www.httprecipes.com");
}
catch(MalformedURLException e)
{
System.out.println("This URL is not valid.");
}
The
MalformedURLException
will be thrown if the provided URL is invalid. For
example, a URL such as the following would throw the exception:
http:////www.httprecipes.com/
The above URL would throw the exception, because the URL has four slashes (////),
which is not valid. It is important to remember that the
URL
class only checks to see if the
URL is valid. It does NOT check to see if the URL actually exists on the Internet. Existence
of the URL will not be verified until a connection is made. The next section discusses how to
open a connection.
Opening the Stream
Java uses streams to access files and perform other I/O operations. When you access the
URL, you will be given an
InputStream
. This
InputStream
is used to download the
contents of the URL. The
URL
class makes it easy to open a stream for the URL. To open a
stream, you simply use the
openStream
function, provided by the
URL
class. The follow-
ing code shows how this is done.
try
{
URL url = new URL("http://www.httprecipes.com");
InputStream is = url.openStream();
}
catch(MalformedURLException e)
{
System.out.println("Invalid URL");
}
catch(IOException e)
{
System.out.println("Could not connect to URL");
}