O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A Simple HTTP Client

With Example 6-9, we move away from file-based New I/O examples and move into networking examples. HttpGet is a program that performs an HTTP GET request to download a file from a web server. It uses a SocketChannel object for communication with the server, and a FileChannel to store the downloaded data into a file. (Or, if no filename is specified on the command line, it uses the Channels utility class to obtain a WritableByteChannel wrapper around the System.out standard output stream.)

HttpGet uses some networking classes that are new in Java 1.4, but are not part of java.nio. java.net.URI is the most important: it has more powerful URL parsing capabilities than java.net.URL, but does not have the built-in networking capability of the URL class. The other important new class is InetSocketAddress , which encapsulates a hostname and a port.

The HTTP request that is sent to the web server is first built as a String, then wrapped in a CharBuffer, which is encoded into a Charset object. The resulting ByteBuffer is then sent to the server using the write( ) method of the SocketChannel. Once the request is sent, the program enters a loop to read response data from the server and copy that data into the destination file (or standard output channel). The basic loop is essentially the same as the one in Example 6-4, but is complicated by code that extracts the HTTP status code from the response and scans for the byte sequence that identifies the end of the HTTP headers ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required