标签:style blog http color io os 使用 java ar
使用java的NIO来构造http请求体,并且取得响应内容。
package com.test.nio; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; public class TestSocketForBaidu { /** * @param args * @throws Exception */ private static Charset charset = Charset.forName("UTF8");// 创建GBK字符集 public static void main(String[] args) throws Exception { SocketChannel channel=SocketChannel.open(new InetSocketAddress("www.itbuluoge.com",80)); String line="GET / HTTP/1.1 \r\n"; line+="HOST:www.itbuluoge.com\r\n"; line+="\r\n"; channel.write(charset.encode(line)); ByteBuffer buffer = ByteBuffer.allocate(1024);// 创建1024字节的缓冲 int size=channel.read(buffer); while(size!=-1) { buffer.flip(); while(buffer.hasRemaining()) { System.out.print(charset.decode(buffer)); } buffer.clear(); size=channel.read(buffer); } } }
我们可以看到,能够返回网站的首页,而且能够解析正文,这里要注意一下,构造http请求的时候,最少需要的协议或者说参数是:
GET / HTTP/1.1
Host: www.itbuluoge.com
标签:style blog http color io os 使用 java ar
原文地址:http://blog.csdn.net/itbuluoge/article/details/39577395