Java Reference
In-Depth Information
{
System.out.println("Unknown protocol URL");
}
If an invalid URL was provided, then a MalformedURLException will be
thrown.
} catch (MalformedURLException e)
{
System.out.println("Invalid URL");
If any other sort of error occurs while connecting to the URL, an IOException will
be thrown.
} catch (IOException e)
{
System.out.println("Error connecting to URL");
}
This recipe will be rarely used; however, it demonstrates one practical purpose of using
the HttpsURLConnection object directly.
Recipe #5.2: HTTP Authentication
The next recipe is very useful if you need to retrieve data from a site that requires HTTP
authentication. First, the code downloads the contents of a URL and then saves it to a local
file. This recipe can be used either in whole are in part.
Used in its entirety, this recipe provides a method, named download . This method
requires the URL to download, the local file to save to, and the user id and password. The
download method will then download the contents. If the user id or password is invalid,
an exception will be thrown.
If your application doesn't call for downloading directly to a file, you could use part of this
recipe. Perhaps your application needs only to parse data at an HTTP authenticated site. If this
is the case, you should copy the addAuthHeaders method. This method requires an
HttpURLConnection object, and a user id and password. The addAuthHeaders
method then adds the correct HTTP request header for the specified user id and password.
I have used this recipe in both ways for several bots that required HTTP authenticated
access. The program is shown in Listing 5.2.
Search WWH ::




Custom Search