Reading the Contents of a URL
Problem
You want to read the contents of a URL (which can include a CGI, 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 ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.