public class SendRequest extends Thread{
private String host;
private int port;
private String url;
SendRequest(String host,int port, String url){
this.host = host;
this.port = port;
this.url = url;
}
public void run() {
sendRequest(host,port, url);
}
public void sendRequest(String host,int port, String url) {
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//socketChannel.pipeline().addLast(new HttpRequestEncoder());// 客户端对发送的httpRequest进行编码
//socketChannel.pipeline().addLast(new HttpResponseDecoder());// 客户端需要对服务端返回的httpresopnse解码
socketChannel.pipeline().addLast("codec", new HttpClientCodec());
socketChannel.pipeline().addLast("httpAggregator",new HttpObjectAggregator(512*1024)); // http 消息聚合器
socketChannel.pipeline().addLast(new GetResponse());
}
});
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url);
// 构建http请求
request.headers().set(HttpHeaderNames.HOST, host);
request.headers().set(HttpHeaderNames.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0");
request.headers().set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
request.headers().set(HttpHeaderNames.ACCEPT_LANGUAGE, "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
request.headers().set(HttpHeaderNames.CONNECTION, "close");
Channel channel = bootstrap.connect(host,port).sync().channel();
// send request
channel.writeAndFlush(request).sync();
channel.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
}
}
// *** 获取原本的response数据 ***
private class GetResponse extends ChannelInboundHandlerAdapter {
private HttpResponse response;
private HttpContent content;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
boolean flag = true;
//匹配响应请求
if (msg instanceof HttpResponse) {
flag = false;
//*** 将response保存到成员变量中 ***
this.response = (HttpResponse) msg;
}
if (msg instanceof HttpContent) {
flag = false;
//*** 将content保存到成员变量中 ***
this.content = (HttpContent) msg;
}
if(flag) {
System.out.println("!!!!! 没匹配到 !!!!!");
}
}
}
}