0
点赞
收藏
分享

微信扫一扫

java使用NIO构造http请求

cnlinkchina 2023-03-05 阅读 41


使用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);
}


}

}


输出结果

java使用NIO构造http请求_HTTP


我们可以看到,能够返回网站的首页,而且能够解析正文,这里要注意一下,构造http请求的时候,最少需要的协议或者说参数是:

GET / HTTP/1.1

Host: www.itbuluoge.com


注意,结束一定要是两个“\r\n\r\n”。



举报

相关推荐

0 条评论