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());
    }
}
作者:小念
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/kiko2014551511/p/15252108.html