Reading the Contents of a URL


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


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


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/... ***
   <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... ***

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 ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.