Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata