URL Connections

URL connections are closely related to URLs, as their name implies. Indeed, you get a reference to a URLConnection by using the openConnection( ) method of a URL object; in many ways, the URL class is only a wrapper around the URLConnection class. URL connections provide more control over the communication between the client and the server. In particular, URL connections provide not just input streams by which the client can read data from the server, but also output streams to send data from the client to the server.

The java.net.URLConnection class is an abstract class that handles communication with different kinds of servers, such as FTP servers and web servers. Protocol-specific subclasses of URLConnection, which are hidden inside the sun packages, handle different kinds of servers.

5.2.1. Reading Data from URL Connections

URL connections take place in five steps:

  1. The URL object is constructed.
  2. The openConnection( ) method of the URL object creates the URLConnection object.
  3. The parameters for the connection and the request properties that the client sends to the server are set up.
  4. The connect( ) method makes the connection to the server, perhaps using a socket for a network connection or a file input stream for a local connection. The response header information is read from the server.
  5. Data is read from the connection using the input stream returned by getInputStream( ) or a content handler returned by getContent( ). Data can be sent to the server using the output stream provided by getOutputStream( ).

This scheme is very much based on the HTTP protocol. It does not fit other schemes that have a more interactive "request, response, request, response, request, response" pattern instead of HTTP/1.0's "single request, single response, close connection" pattern. In particular, FTP doesn't really fit this pattern.

URLConnection objects are not constructed directly in your own programs. Instead, you create a URL for the particular resource and call that URL's openConnection( ) method. This gives you a URLConnection. Then the getInputStream( ) method returns an input stream that reads data from the URL. (The openStream( ) method of the URL class is just a thin veneer over the getInputStream( ) method of the URLConnection class.) If the connection cannot be opened, for example because the remote host is unreachable, connect( ) throws an IOException. For example, this code repeats the main body of Example 5-1 using a URLConnection to open the stream:

 URL u = new URL(args[0]);
 URLConnection connection = u.openConnection( );
 in = connection.getInputStream( );
 for (int c = in.read(); c != -1; c = in.read( )) {


5.2.2. Writing Data on URL Connections

Writing data to a URLConnection is similar to reading data. However, you must first inform the URLConnection that you plan to use it for output. Then, instead of getting the connection's input stream and reading from it, you get the connection's output stream and write to it. This is commonly used for HTTP POST and PUT. Here are the steps for writing data on a URLConnection:

  1. Construct the URL object.
  2. Call the openConnection( ) method of the URL object to create the URLConnection object.
  3. Pass true to setDoOutput( ) to indicate that this URLConnection will be used for output.
  4. If you also want to read input from the stream, invoke setDoInput(true) to indicate that this URLConnection will be used for input.
  5. Create the data you want to send, preferably as a byte array.
  6. Call getOutputStream( ) to get an output stream object. Write the byte array calculated in step 5 onto the stream.
  7. Close the output stream.
  8. Call getInputStream( ) to get an input stream object. Read and write it as usual.

Example 5-2 uses these steps to implement a simple mail client. It forms a mailto URL from an email address entered on the command line. Input for the message is copied from System.in onto the output stream of the URLConnection using a StreamCopier. The end-of-stream character signals the end of the message.

Example 5-2. The MailClient class

import java.net.*;
import java.io.*;
public class MailClient {
 public static void main(String[] args) {
 if (args.length == 0) {
 System.err.println("Usage: java MailClient username@host.com");
 try {
 URL u = new URL("mailto:" + args[0]);
 URLConnection uc = u.openConnection( );
 uc.connect( );
 OutputStream out = uc.getOutputStream( );
 for (int c = System.in.read(); c != -1; c = System.in.read( )) {
 out.close( );
 catch (IOException ex) {

For example, to send email to the author of this book:

$ java MailClient elharo@metalab.unc.edu
hi there!

MailClient suffers from a few restrictions. The proper way to detect the end of the message is to look for a period on a line by itself. Proper or not, that style of user interface is really antiquated, so I didn't bother to implement it. To do so properly, you'll need to use a Reader or a Writer; they're discussed in Chapter 20. Furthermore, it works only in Java environments that support the mailto protocol; thus, it works under Sun's JDK but may not work in other VMs. It also requires that the local host be running an SMTP server, or that the system property mail.host must contain the name of an accessible SMTP server, or that a machine in the local domain named mailhost be running an SMTP server. Finally, the security manager must permit network connections to that server, although this is not normally a problem in an application.

Basic I/O

Introducing I/O

Output Streams

Input Streams

Data Sources

File Streams

Network Streams

Filter Streams

Filter Streams

Print Streams

Data Streams

Streams in Memory

Compressing Streams

JAR Archives

Cryptographic Streams

Object Serialization

New I/O



Nonblocking I/O

The File System

Working with Files

File Dialogs and Choosers


Character Sets and Unicode

Readers and Writers

Formatted I/O with java.text


The Java Communications API


The J2ME Generic Connection Framework


Character Sets

Java I/O
Java I/O
ISBN: 0596527500
EAN: 2147483647
Year: 2004
Pages: 244

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net