Java Reference
In-Depth Information
URLConnection does not have the best-designed API in the Java class
library. One of several problems is that the URLConnection class is too
closely tied to the HTTP protocol. For instance, it assumes that each
file transferred is preceded by a MIME header or something very much
like one. However, most classic protocols such as FTP and SMTP don't
use MIME headers.
Opening URLConnections
A program that uses the URLConnection class directly follows this basic sequence of
steps:
1. Construct a URL object.
2. Invoke the URL object's openConnection() method to retrieve a URLConnection
object for that URL.
3. Configure the URLConnection .
4. Read the header fields.
5. Get an input stream and read data.
6. Get an output stream and write data.
7. Close the connection.
You don't always perform all these steps. For instance, if the default setup for a particular
kind of URL is acceptable, you can skip step 3. If you only want the data from the server
and don't care about any metainformation, or if the protocol doesn't provide any met‐
ainformation, you can skip step 4. If you only want to receive data from the server but
not send data to the server, you'll skip step 6. Depending on the protocol, steps 5 and 6
may be reversed or interlaced.
The single constructor for the URLConnection class is protected:
protected URLConnection ( URL url )
Consequently, unless you're subclassing URLConnection to handle a new kind of URL
(i.e., writing a protocol handler), you create one of these objects by invoking the open
Connection() method of the URL class. For example:
try {
URL u = new URL ( "http://www.overcomingbias.com/" );
URLConnection uc = u . openConnection ();
// read from the URL...
} catch ( MalformedURLException ex ) {
System . err . println ( ex );
} catch ( IOException ex ) {
Search WWH ::




Custom Search