The URLConnection class is the main interface for accessing web documents. It has one static method named Open that takes the URL of the document to be acccessed, and returns an InputStream object that can be used to read the contents of the document. The URL can be either an HTTP URL or a file URL. Examples are "http://www.cnn.com/index.html" and "file:/public_html/index.html".
The InputStream object returned by URLConnection::Open provides methods for reading the data stored in the web document, and to close the stream when the program has finished reading the document's data. The following code fragment shows how to read a web document and print its contents to standard output.
#include "URLConnection.h" InputStream * doc = URLConnection::Open("http://www.cnn.com/index.html"); while (!doc->IsDone()) { char c = doc->Read(); cout << c; } doc->Close(); delete doc;InputStream is an abstract interface for reading data from a stream. There are two classes that implement the InputStream interface, FileInputStream and HTTPInputStream. If the URL passed to URLConnection::Open is a file URL, the InputStream object returned is a FileInputStream object. If the URL is an HTTP URL, the InputStream object returned is an HTTPInputStream object. You need not be concerned directly with the FileInputStream and HTTPInputStream classes. URLConnection::Open takes care of deciding which kind of object to create. Your code need not even know what kind of URL is being processed, file or HTTP. It just needs to make sure that the InputStream returned by URLConnection::Open is eventually closed and deleted.
There are many kinds of error conditions that can occur when a program accesses documents on the web. The methods on the web access classes throw exceptions when errors occur. Examples of exceptions that might be thrown are: InvalidURLException, FileException, NetworkException, and IllegalStateException. Your code must be prepared to handle these exceptions when they occur, or your program will terminate abnormally.
The classes that provide the web access functions are described below.
If the stream is closed, an IllegalStateException is thrown.
If the last byte has already been read from the stream, an IllegalStateException is thrown.
Depending on the type of the InputStream, this method could throw any of the following exceptions: FileException, NetworkException, IllegalStateException.
Any of the following exceptions may be thrown by this method: InvalidURLException, FileException, NetworkException, IllegalStateException.