HttpClient

  1. public class HttpClient {
  2. public static final String HOST = "127.0.0.1";
  3. private static final boolean SSL = false;
  4. public void connect(String host, int port) throws Exception {
  5. EventLoopGroup workerGroup = new NioEventLoopGroup();
  6. try {
  7. Bootstrap b = new Bootstrap();
  8. b.group(workerGroup);
  9. b.channel(NioSocketChannel.class);
  10. b.option(ChannelOption.SO_KEEPALIVE, true);
  11. b.handler(new ChannelInitializer<SocketChannel>() {
  12. @Override
  13. public void initChannel(SocketChannel ch) throws Exception {
  14. ch.pipeline().addLast(new HttpClientCodec());
  15. /*聚合http为一个完整的报文*/
  16. ch.pipeline().addLast("aggregator",
  17. new HttpObjectAggregator(10*1024*1024));
  18. /*解压缩*/
  19. ch.pipeline().addLast("decompressor",
  20. new HttpContentDecompressor());
  21. ch.pipeline().addLast(new HttpClientInboundHandler());
  22. }
  23. });
  24. // Start the client.
  25. ChannelFuture f = b.connect(host, port).sync();
  26. f.channel().closeFuture().sync();
  27. } finally {
  28. workerGroup.shutdownGracefully();
  29. }
  30. }
  31. public static void main(String[] args) throws Exception {
  32. HttpClient client = new HttpClient();
  33. client.connect("127.0.0.1", HttpServer.port);
  34. }
  35. }

HttpClientInboundHandler

  1. public class HttpClientInboundHandler extends ChannelInboundHandlerAdapter {
  2. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  3. FullHttpResponse httpResponse = (FullHttpResponse)msg;
  4. System.out.println(httpResponse.status());
  5. System.out.println(httpResponse.headers());
  6. ByteBuf buf = httpResponse.content();
  7. System.out.println(buf.toString(CharsetUtil.UTF_8));
  8. httpResponse.release();
  9. }
  10. @Override
  11. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  12. URI uri = new URI("/test");
  13. String msg = "Hello";
  14. DefaultFullHttpRequest request =
  15. new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
  16. HttpMethod.GET,
  17. uri.toASCIIString(),
  18. Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));
  19. // 构建http请求
  20. request.headers().set(HttpHeaderNames.HOST, HttpClient.HOST);
  21. request.headers().set(HttpHeaderNames.CONNECTION,
  22. HttpHeaderValues.KEEP_ALIVE);
  23. request.headers().set(HttpHeaderNames.CONTENT_LENGTH,
  24. request.content().readableBytes());
  25. // 发送http请求
  26. ctx.writeAndFlush(request);
  27. }
  28. }