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. The following small Java program uses openStream() to get an input stream on the URL "http://www.yahoo.com/". It then reads the contents from the input stream echoing 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 = new DataInputStream(yahoo.openStream());
            String inputLine;

            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.

Or, you might see the following error message:

IOException: java.net.UnknownHostException: www.yahoo.com
The above message indicates that you may have to set the proxy host so that the program can find the www.yahoo.com server. (If necessary, ask your system administrator for the proxy host on your network.)


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