Reading Data from a Server
The minimal set of steps needed to
retrieve data from a URL using a URLConnection
object are these:
Construct a
URL
object.Invoke the
URL
object’sopenConnection( )
method to retrieve aURLConnection
object for that URL.Invoke the
URLConnection
’sgetInputStream( )
method.Read from the input stream using the usual stream API.
The getInputStream( )
method returns a generic
InputStream
, which lets you read and parse the
data that the server sends yourself.
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.*; 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 e) { System.err.println(args[0] + " is not a parseable URL"); } catch (IOException e) { System.err.println(e); } } // end if } // end main } // end SourceViewer2
It is no accident that this program is almost the same as Example 15.5. The openStream( )
method
of the URL
class just returns an
InputStream
from its own
URLConnection
object. The output ...
Get Java Network Programming, Second Edition 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.