15.2 Reading Data from a Server
Here is the minimal set of steps needed to retrieve data from a URL
using a
URLConnection object:Construct a URL object.Invoke the URL object's
openConnection( ) method to retrieve a
URLConnection object for that URL.Invoke the URLConnection's
getInputStream( ) method.Read from the input stream using the usual stream API.The getInputStream() method returns a generic
InputStream that lets you read and parse the data
that the server sends.
public InputStream getInputStream( )Example 15-1 uses the getInputStream() method to download a web page.
Example 15-1. Download a web page with a URLConnection
import java.net.*;It is no accident that this program is almost the same as Example
import java.io.*;
public class SourceViewer2 {
public static void main (String[] args) {
if (args.length > 0) {
try {
//Open the URLConnection for reading
URL u = new URL(args[0]);
URLConnection uc = u.openConnection( );
InputStream raw = uc.getInputStream( );
InputStream buffer = new BufferedInputStream(raw);
// chain the InputStream to a Reader
Reader r = new InputStreamReader(buffer);
int c;
while ((c = r.read( )) != -1) {
System.out.print((char) c);
}
}
catch (MalformedURLException ex) {
System.err.println(args[0] + " is not a parseable URL");
}
catch (IOException ex) {
System.err.println(ex);
}
} // end if
} // end main
} // end SourceViewer2
7-5. The openStream( ) method of the
URL class just returns an
InputStream from its own
URLConnection object. The output is identical as
well, so I won't repeat it here.The differences between
URL and URLConnection
aren't apparent with just a simple input stream as
in this example. The biggest differences between the two classes are:URLConnection provides access to the HTTP header.URLConnection can configure the request parameters
sent to the server.URLConnection can write data to the server as well
as read data from the server.
• Table of Contents• Index• Reviews• Reader Reviews• Errata• AcademicJava Network Programming, 3rd EditionBy
Elliotte Rusty Harold Publisher: O'ReillyPub Date: October 2004ISBN: 0-596-00721-3Pages: 706
Thoroughly revised to cover all the 100+ significant updates
to Java Developers Kit (JDK) 1.5, Java Network
Programming is a complete introduction to
developing network programs (both applets and applications)
using Java, covering everything from networking fundamentals
to remote method invocation (RMI). It includes chapters on
TCP and UDP sockets, multicasting protocol and content
handlers, servlets, and the new I/O API. This is the
essential resource for any serious Java developer.