Skip to Content
Java Network Programming, Second Edition
book

Java Network Programming, Second Edition

by Elliotte Rusty Harold
August 2000
Intermediate to advanced
760 pages
21h
English
O'Reilly Media, Inc.
Content preview from Java Network Programming, Second Edition

Reading Data from a Server

The minimal set of steps needed to retrieve data from a URL using a URLConnection object are these:

  1. Construct a URL object.

  2. Invoke the URL object’s openConnection( ) method to retrieve a URLConnection object for that URL.

  3. Invoke the URLConnection’s getInputStream( ) method.

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

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

Java Network Programming, 4th Edition

Java Network Programming, 4th Edition

Elliotte Rusty Harold
Java Concurrency, 2/e

Java Concurrency, 2/e

Douglas Schmidt

Publisher Resources

ISBN: 1565928709Supplemental ContentCatalog PageErrata