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());
        }
    }
    作者:小念
    本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
  • 相关阅读:
    安卓笔记:Android 界面设计指南——人人都是产品经理就是个玩笑话
    Windows CMD 命令
    安卓开发:dex 文件反编译
    VBA 学习笔记 运算符
    工商管理同等学力申硕全国统一考试资料整理
    VBA 学习笔记 判断语句、循环
    VBA 学习笔记 日期时间函数
    安卓自动领水果福气
    【合集】人大商学院同等学力工商管理
    安卓笔记:进度设计原则和常见错误
  • 原文地址:https://www.cnblogs.com/kiko2014551511/p/15252108.html
Copyright © 2011-2022 走看看