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

Get Java Examples in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.