The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search

Trail: Custom Networking
Lesson: Working with URLs

Reading from and Writing to a URLConnection

If you've successfully used openConnection to initiate communications with a URL, then you have a reference to a URLConnection object. The URLConnection class contains many methods that let you communicate with the URL over the network. URLConnection is an HTTP-centric class; that is, many of its methods are useful only when you are working with HTTP URLs. However, most URL protocols allow you to read from and write to the connection. This section describes both functions.

Reading from a URLConnection

The following program performs the same function as the URLReader program shown in Reading Directly from a URL.

However, rather than getting an input stream directly from the URL, this program explicitly opens a connection to a URL and gets an input stream from the connection. Then, like URLReader, this program creates a BufferedReader on the input stream and reads from it. The bold statements highlight the differences between this example and the previous

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL yahoo = new URL("http://www.yahoo.com/");
        URLConnection yc = yahoo.openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                yc.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}
The output from this program is identical to the output from the program that opens a stream directly from the URL. You can use either way to read from a URL. However, reading from a URLConnection instead of reading directly from a URL might be more useful. This is because you can use the URLConnection object for other tasks (like writing to the URL) at the same time.

Again, if the program hangs or you see an error message, you may have to set the proxy host so that the program can find the Yahoo server.

Writing to a URLConnection

Many HTML pages contain forms-- text fields and other GUI objects that let you enter data to send to the server. After you type in the required information and initiate the query by clicking a button, your Web browser writes the data to the URL over the network. At the other end, a cgi-bin script (usually) on the server receives the data, processes it, and then sends you a response, usually in the form of a new HTML page.

Many cgi-bin scripts use the POST METHOD for reading the data from the client. Thus writing to a URL is often called posting to a URL. Server-side scripts use the POST METHOD to read from their standard input.


Note:  Some server-side cgi-bin scripts use the GET METHOD to read your data. The POST METHOD is quickly making the GET METHOD obsolete because it's more versatile and has no limitations on the amount of data that can be sent through the connection.

A Java program can interact with cgi-bin scripts also on the server side. It simply must be able to write to a URL, thus providing data to the server. It can do this by following these steps:

  1. Create a URL.
  2. Open a connection to the URL.
  3. Set output capability on the URLConnection.
  4. Get an output stream from the connection. This output stream is connected to the standard input stream of the cgi-bin script on the server.
  5. Write to the output stream.
  6. Close the output stream. Hassan Schroeder, a member of the Java development team, wrote a small cgi-bin script named backwards and made it available at the Java Web site, http://java.sun.com/cgi-bin/backwards. You can use this script to test the following example program. You can also put the script on your network, name it backwards, and test the program locally.

    The script at our Web site reads a string from its standard input, reverses the string, and writes the result to its standard output. The script requires input of the form string=string_to_reverse, where string_to_reverse is the string whose characters you want displayed in reverse order.

    Here's an example program that runs the backwards script over the network through a URLConnection:

    import java.io.*;
    import java.net.*;
    
    public class Reverse {
        public static void main(String[] args) throws Exception {
    
    	if (args.length != 1) {
    	    System.err.println("Usage:  java Reverse "
                                   + "string_to_reverse");
    	    System.exit(1);
    	}
    
    	String stringToReverse = URLEncoder.encode(args[0]);
    
    	URL url = new URL("http://java.sun.com/cgi-bin/backwards");
    	URLConnection connection = url.openConnection();
    	connection.setDoOutput(true);
    
    	PrintWriter out = new PrintWriter(
                                  connection.getOutputStream());
    	out.println("string=" + stringToReverse);
    	out.close();
    
    	BufferedReader in = new BufferedReader(
    				new InputStreamReader(
    				connection.getInputStream()));
    	String inputLine;
    
    	while ((inputLine = in.readLine()) != null)
    	    System.out.println(inputLine);
    
    	in.close();
        }
    }
    
    Let's examine the program and see how it works. First, the program processes its command-line arguments:
    if (args.length != 1) {
        System.err.println("Usage:  java Reverse " +
                           "string_to_reverse");
        System.exit(-1);
    }
    String stringToReverse = URLEncoder.encode(args[0]);
    
    These statements ensure that the user provides one and only one command-line argument to the program, and then encodes it. The command-line argument is the string that will be reversed by the cgi-bin script backwards. It may contain spaces or other non-alphanumeric characters. These characters must be encoded because the string is processed on its way to the server. The URLEncoder class methods encode the characters.

    Next, the program creates the URL object--the URL for the backwards script on java.sun.com--opens a URLConnection, and sets the connection so that it can write to it:

    URL url = new URL("http://java.sun.com/cgi-bin/backwards");
    URLConnection c = url.openConnection();
    c.setDoOutput(true);
    
    The program then creates an output stream on the connection and opens a PrintWriter on it:
    PrintWriter out = new PrintWriter(c.getOutputStream());
    
    If the URL does not support output, getOutputStream method throws an UnknownServiceException. If the URL does support output, then this method returns an output stream that is connected to the standard input stream of the URL on the server side--the client's output is the server's input.

    Next, the program writes the required information to the output stream and closes the stream:

    out.println("string=" + stringToReverse);
    out.close();
    
    This code writes to the output stream using the println method. So you can see that writing data to a URL is as easy as writing data to a stream. The data written to the output stream on the client side is the input for the backwards script on the server side. The Reverse program constructs the input in the form required by the script by concatenating string= to the encoded string to be reversed.

    Often, when you are writing to a URL, you are passing information to a cgi-bin script, as in this example. This script reads the information you write, performs some action, and then sends information back to you via the same URL. So it's likely that you will want to read from the URL after you've written to it. The Reverse program does this:

    BufferReader in = new BufferedReader(
                          new InputStreamReader(c.getInputStream()));
    String inputLine;
    
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();
    
    When you run the Reverse program using "Reverse Me" as an argument, you should see this output:
    Reverse Me
     reversed is: 
    eM esreveR
    

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search