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

Reading Directly from a URL (1.1notes)

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 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 "". It then reads the contents from the input stream echoing the contents to the display.


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

            while ((inputLine = dis.readLine()) != null) {
        } 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 "" scrolling by in your command window.

Or, you might see the following error message:

The above message indicates that you may have to set the proxy host so that the program can find the 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