|
New I/0 Functionality for JavaTM 2 Standard Edition 1.4(8) Once connected, you can read from or write to the channel with ByteBuffer objects. For instance, you can wrap a String in a CharBuffer with the help of an CharsetEncoder to send an HTTP request: Charset charset = Charset.forName("ISO-8859-1");CharsetEncoder encoder = charset.newEncoder();String request = "GET / \n\r\n\r";channel.write(encoder.encode(CharBuffer.wrap(request)));You can then read the response from the channel. Since the response for this HTTP request will be text, you'll need to convert that response into a CharBuffer through a CharsetDecoder. By creating just a CharBuffer to start, you can keep reusing the object to avoid unnecessary garbage collection between reads: ByteBuffer buffer = ByteBuffer.allocateDirect(1024);CharBuffer charBuffer = CharBuffer.allocate(1024);while ((channel.read(buffer)) != -1) {buffer.flip();decoder.decode(buffer, charBuffer, false);charBuffer.flip();System.out.println(charBuffer);buffer.clear();charBuffer.clear();}The following program connects all these pieces to read the main page of a Web site through an HTTP request. Feel free to save the output to a file to compare the results to viewing the page with a browser. import Java.io.*;import Java.net.*;import Java.nio.*;import Java.nio.channels.*;import Java.nio.charset.*;public class ReadURL {public static void main(String args[]) { String host = args[0]; SocketChannel channel = null; try {// SetupInetSocketAddress socketAddress =new InetSocketAddress(host, 80);Charset charset =Charset.forName("ISO-8859-1");CharsetDecoder decoder =charset.newDecoder();CharsetEncoder encoder =charset.newEncoder();// Allocate buffersByteBuffer buffer =ByteBuffer.allocateDirect(1024);CharBuffer charBuffer =CharBuffer.allocate(1024);// Connectchannel = SocketChannel.open();channel.connect(socketAddress);// Send requestString request = "GET / \n\r\n\r";channel.write(encoder.encode(CharBuffer.wrap(request)));// Read responsewhile ((channel.read(buffer)) != -1) {buffer.flip();// Decode bufferdecoder.decode(buffer, charBuffer, false);// DisplaycharBuffer.flip();System.out.println(charBuffer);buffer.clear();charBuffer.clear();} } catch (UnknownHostException e) {System.err.println(e); } catch (IOException e) {System.err.println(e); } finally {if (channel != null) {try { channel.close();} catch (IOException ignored) {}} }}}Non-Blocking Reads
|