Reading Data from a URL

public final InputStream openStream() throws IOException

The openStream() method opens a connection to the server specified in the URL and returns an InputStream fed by the data from that connection. This allows you to download data from the server. Any headers that come before the actual data or file requested are stripped off before, the stream is opened. You get only raw data.

You read from the input stream using the methods of java.io discussed in Week 10. Note that most network connections are considerably less reliable and slower sources of data than files. Buffering, either via a BufferedInputStream or a BufferedReader, is important.

The following example reads a series of host names and URLs from the command line. It attempts to form a URL from each command line argument, connect to the specified server, and download the data, which is then printed on System.out.

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


public class Webcat {

  public static void main(String[] args) {

    for (int i = 0; i < args.length; i++) {
      try {
        URL u = new URL(args[i]);
        InputStream is = u.openStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String theLine;
        while ((theLine = br.readLine()) != null) {
          System.out.println(theLine);
        }
      }
      catch (MalformedURLException ex) {
        System.err.println(ex);
      } 
      catch (IOException ex) {
        System.err.println(ex);      
      } 
      
    }

  }

}

Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified April 16, 1997