Working with URLs |
After you've successfully created a URL, you can call the URL'sopenStream()
method to get a stream from which you can read the contents of the URL. TheopenStream()
method returns a java.io.InputStream object so you can read from a URL using the normal InputStream methods. Input and Output Streams 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.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.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); } } }If, instead, you see the following error message:
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.)IOException: java.net.UnknownHostException: www.yahoo.comYou can proxy host through the command line when you run the program, like this:
java -DproxySet=true -DproxyHost=proxyhost OpenStreamTest
Working with URLs |