zoukankan      html  css  js  c++  java
  • Netty实现Http客户端

    1、Client 建立连接

    package com.bokeyuan.http.client;
    
    import io.netty.bootstrap.Bootstrap;
    import io.netty.channel.*;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.nio.NioSocketChannel;
    import io.netty.handler.codec.http.*;
    
    import java.net.InetSocketAddress;
    
    
    /**
     * @author: void
     * @date: 2021-09-10 15:27
     * @description: 客户端 建立连接
     * @version: 1.0
     */
    public class Client {
    
    
        private String ip;
        private int port;
    
        public Client(String ip, int port) {
            this.ip = ip;
            this.port = port;
        }
    
    
        public  void start() throws InterruptedException {
    
            //线程组
            EventLoopGroup group = new NioEventLoopGroup();
            //启动类
            Bootstrap bootstrap = new Bootstrap();
            try {
                bootstrap.group(group)
                        .remoteAddress(new InetSocketAddress(ip, port))
                        //长连接
                        .option(ChannelOption.SO_KEEPALIVE, true)
                        .channel(NioSocketChannel.class)
                        .handler(new ChannelInitializer<Channel>() {
                            @Override
                            protected void initChannel(Channel channel) throws Exception {
    
                                //包含编码器和解码器
                                channel.pipeline().addLast(new HttpClientCodec());
    
                                //聚合
                                channel.pipeline().addLast(new HttpObjectAggregator(1024 * 10 * 1024));
    
                                //解压
                                channel.pipeline().addLast(new HttpContentDecompressor());
    
                                channel.pipeline().addLast(new ClientHandler());
                            }
                        });
    
                ChannelFuture channelFuture = bootstrap.connect().sync();
    
                channelFuture.channel().closeFuture().sync();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                group.shutdownGracefully();
            }
        }
    
        public static void main(String[] args) throws InterruptedException {
            Client client = new Client("127.0.0.1",8899);
            client.start();
    
        }
    
    }

    2、ClientHandler  发送http请求

    channelActive()中发送http请求,channelRead()方法中处理响应报文

    package com.chenly.bokeyuan.http.client;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.handler.codec.http.*;
    import io.netty.util.CharsetUtil;
    
    import java.net.URI;
    import java.nio.charset.StandardCharsets;
    
    /**
     * @author: void
     * @date: 2021-09-10 15:28
     * @description:
     * @version: 1.0
     */
    public class ClientHandler extends ChannelInboundHandlerAdapter {
    
        /**
         * 客户端与服务端建立连接时执行
         * @param ctx
         * @throws Exception
         */
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            //发送请求至服务端
    
            URI url = new URI("/test");
            String msg = "hello";
    
            //配置HttpRequest的请求数据和一些配置信息
            FullHttpRequest request = new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1,
                    HttpMethod.GET,
                    url.toASCIIString(),
                    Unpooled.wrappedBuffer(msg.getBytes(StandardCharsets.UTF_8)));
    
            request.headers()
                    .set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=UTF-8")
                    //开启长连接
                    .set(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE)
                    //设置传递请求内容的长度
                    .set(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes());
    
            ctx.writeAndFlush(request);
        }
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            FullHttpResponse response = (FullHttpResponse) msg;
            ByteBuf content = response.content();
            HttpHeaders headers = response.headers();
            System.out.println("content:"+content.toString(CharsetUtil.UTF_8));
            System.out.println("headers:"+headers.get("content-type").toString());
        }
    }
    作者:小念
    本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
  • 相关阅读:
    Database mirroring connection error 4 'An error occurred while receiving data: '10054(An existing connection was forcibly closed by the remote host.)
    [转载]——Automatic Tuning of Undo_retention Causes Space Problems (文档 ID 420525.1)
    [转载]——Full UNDO Tablespace In 10gR2 and above (文档 ID 413732.1)
    SQL Server Agent作业执行CmdExec(bat)命令报权限问题
    SQL Server有意思的数据类型隐式转换问题
    pymssql的Connection相关特性浅析
    pymssql默认关闭自动模式开启事务行为浅析
    Azure上MySQL的离线备份:将备份拷贝到Azure Blob上
    crontab中部署Python脚本注意事项
    TypeError: expected string or bytes-like object
  • 原文地址:https://www.cnblogs.com/kiko2014551511/p/15252108.html
Copyright © 2011-2022 走看看