Java Reference
In-Depth Information
if (args.length != 2)
{
System.out.println(
"Usage: \njava DownloadURL [URL to Download] [Output File]");
} else
{
DownloadURL d = new DownloadURL();
d.download(args[0], args[1]);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
To run this program you must specify the URL to download and the local file. For example,
to download the contents of http://www.httprecipes.com to the file local.html ,
you would use the following command:
DownloadURL http://www.httprecipes.com/ local.html
The above command simply shows the abstract format to call this recipe, with the ap-
propriate parameters. For exact information on how to run this recipe refer to Appendix B,
C, or D, depending on the operating system you are using. This program makes use of the
following two methods that were first introduced in Chapter 3.
• downloadText
• downloadBinary
These two methods are exactly the same as the ones used in Chapter 3; therefore, they
will not be discussed again here. If you would like more information about these two func-
tions, refer to Chapter 3.
The example presented here connects to the specified URL and determines the type of
that URL. Once the type is determined, the URL is downloaded by calling the appropriate
download method, either downloadText or downloadBinary .
To begin, the downloadURL method creates an HttpURLConnection object
to the specified URL. Then, an InputStream is created to receive the contents of the
URL and an OutputStream is created to write the downloaded data to a file.
HttpURLConnection http = (HttpURLConnection) remoteURL.openConnec-
tion();
InputStream is = http.getInputStream();
OutputStream os = new FileOutputStream(localFile);
Search WWH ::




Custom Search