Previous | Next | Trail Map | Custom Networking and Security | Working with URLs


Reading Directly from a URL

After you've successfully created a URL, you can call the URL's openStream() method to get a stream from which you can read the contents of the URL. The openStream() method returns a java.io.InputStream(in the API reference documentation)object so you can read from a URL using the normal InputStream methods. Input and Output Streams(in the Writing Java Programs trail)describes the I/O classes provided by the Java development environment and shows you how to use them.

Reading from a URL is as easy as reading from an input stream. This small Java program uses openStream() to get an input stream on the URL "http://www.yahoo.com/", read the contents from the input stream, and then echo the contents to the display.

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

class OpenStreamTest {
    public static void main(String args[]) {
        try {
            URL yahoo = new URL("http://www.yahoo.com/");
            DataInputStream dis;
            String inputLine;

            dis = new DataInputStream(yahoo.openStream());
            while ((inputLine = dis.readLine()) != null) {
                System.out.println(inputLine);
            }
            dis.close();
        } catch (MalformedURLException me) {
            System.out.println("MalformedURLException: " + me);
        } catch (IOException ioe) {
            System.out.println("IOException: " + ioe);
        }
    }
}
When you run the program you should see the HTML commands and textual content from the HTML file located at "http://www.yahoo.com/" scrolling by in your command window.

If, instead, you see the following error message:

IOException: java.net.UnknownHostException: www.yahoo.com
you may have to set the proxy host so that the program can find the www.yahoo.com server. ([PENDING: insert definition of proxy.] If necessary, ask your system administrator for the proxy host on your network.)

You can proxy host through the command line when you run the program, like this:

java -DproxySet=true -DproxyHost=proxyhost OpenStreamTest


Previous | Next | Trail Map | Custom Networking and Security | Working with URLs