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.InputStreamobject, so you can read from a URL using the normal InputStream methods. Input and Output Streamsdescribes 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.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 = 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); } } }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 www.yahoo.com server. (If necessary, ask your system administrator for the proxy host on your network.)IOException: java.net.UnknownHostException: www.yahoo.com
Working with URLs |