HttpClient
public class HttpClient {
public static final String HOST = "127.0.0.1";
private static final boolean SSL = false;
public void connect(String host, int port) throws Exception {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new HttpClientCodec());
/*聚合http为一个完整的报文*/
ch.pipeline().addLast("aggregator",
new HttpObjectAggregator(10*1024*1024));
/*解压缩*/
ch.pipeline().addLast("decompressor",
new HttpContentDecompressor());
ch.pipeline().addLast(new HttpClientInboundHandler());
}
});
// Start the client.
ChannelFuture f = b.connect(host, port).sync();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
HttpClient client = new HttpClient();
client.connect("127.0.0.1", HttpServer.port);
}
}
HttpClientInboundHandler
public class HttpClientInboundHandler extends ChannelInboundHandlerAdapter {
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
FullHttpResponse httpResponse = (FullHttpResponse)msg;
System.out.println(httpResponse.status());
System.out.println(httpResponse.headers());
ByteBuf buf = httpResponse.content();
System.out.println(buf.toString(CharsetUtil.UTF_8));
httpResponse.release();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
URI uri = new URI("/test");
String msg = "Hello";
DefaultFullHttpRequest request =
new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.GET,
uri.toASCIIString(),
Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));
// 构建http请求
request.headers().set(HttpHeaderNames.HOST, HttpClient.HOST);
request.headers().set(HttpHeaderNames.CONNECTION,
HttpHeaderValues.KEEP_ALIVE);
request.headers().set(HttpHeaderNames.CONTENT_LENGTH,
request.content().readableBytes());
// 发送http请求
ctx.writeAndFlush(request);
}
}