Recipe 18.7 Reading the Contents of a URL


Problem

You want to read the contents of a URL (which can include a CGI script, servlet, etc.).

Solution

Use the URL's openConnection( ) or getContent( ) method. This is not dependent upon being in an applet.

Discussion

The URL class has several methods that allow you to read. The first and simplest, openStream( ) , returns an InputStream that can read the contents directly. The simple TextBrowser program shown here calls openStream( ) and uses this to construct a BufferedReader to read text lines from what is presumed to be a web server. I also demonstrate it reading a local file to show that almost any valid URL can be used:

$ java TextBrowser http://localhost/ *** Loading http://localhost/... *** <html> <head>    <title>Ian Darwin's Webserver On The Road</title>    <link rel="stylesheet" type="text/css" href="/stylesheet.css" title="Style"> </ head> <body bgcolor="#c0d0e0"> <h1>Ian Darwin's Webserver On The Road</h1> ... (rest of body omitted) ... $ java TextBrowser file:///etc/group *** Loading file:///etc/group... *** wheel:*:0:root daemon:*:1:daemon

The next method, openConnection( ), returns a URLConnection object. This allows you more flexibility, providing methods such as getHeaderField( ), getLastModified( ), and other detailed methods. The third URL method, getContent( ), is more general. It returns an object that might be an InputStream, or an object containing the data. Use instanceof to determine which of several types was returned.

See Also

O'Reilly's Java Network Programming by Elliotte Rusty Harold discusses this topic in considerable detail.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net