Netty发送带有body的POST请求

 服务器: Spring boot 启动服务 ( http://127.0.0.1:8080/ )

package org.kayla.rpcfx.provider;

/**
 * @author Kayla(J - doIt)
 * @date 2021/11/25 23:39
 **/
@RestController
@SpringBootApplication
@EnableAspectJAutoProxy
@Slf4j
public class RpcfxServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(RpcfxServerApplication.class, args);
    }

    @Autowired
    RpcfxInvoker invoker;

    @PostMapping("/")
    public RpcfxResponse invoke(@RequestBody RpcfxRequest request) {
        return invoker.invoke(request);
    }
}

客户端: 

package org.kayla.rpcfx.core.client.netty.client;

/**
 * @author Kayla(J - doIt)
 * @date 2021/11/25 23:39
 **/
@Slf4j
public class ClientBootStrap {

    static final String HOST = "127.0.0.1";
    static final int PORT = 8080;

    public static void main(String[] args) throws Exception {

        //创建reactor 线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            //1 设置reactor 线程组
            b.group(workerGroup);
            //2 设置nio类型的channel
            b.channel(NioSocketChannel.class);
            //3 设置监听端口
            b.remoteAddress(HOST, PORT);
            //4 设置通道的参数
            b.option(ChannelOption.SO_KEEPALIVE, true);

            //5 装配通道流水线
            b.handler(new ClientInitializer());

            ChannelFuture f = b.connect();
            f.addListener((ChannelFuture futureListener) ->
            {
                if (futureListener.isSuccess()) {
                    log.info("EchoClient客户端连接成功!");
                } else {
                    log.info("EchoClient客户端连接失败!");
                }
            });

            // 阻塞,直到连接完成
            f.sync();

            Channel channel = f.channel();

            RpcfxRequest request = new RpcfxRequest();
            request.setServiceClass("org.kayla.rpcfx.api.UserService");
            request.setMethod("findById");
            request.setParams(new Object[]{1});
            String reqJson = JSON.toJSONString(request);

            DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                    "/");
            req.setDecoderResult(DecoderResult.SUCCESS);
            req.headers().add(HttpHeaderNames.CONTENT_TYPE, "application/json;charset=UTF-8");
            req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
//            req.headers().add(HttpHeaderNames.ACCEPT, "application/json");
            req.headers().add(HttpHeaderNames.HOST, "127.0.0.1:8080");

            ByteBuf buffer = req.content().clear();
            int p0 = buffer.writerIndex();
            buffer.writeBytes(reqJson.getBytes());
            int p1 = buffer.writerIndex();

            int i = buffer.readableBytes();
            System.out.println("buffer.readableBytes(): " + i);
            System.out.println("p1 - p0: " + (p1 - p0) );

//            req.headers().add(HttpHeaderNames.CONTENT_LENGTH, p1 - p0);
            req.headers().add(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes());

            channel.writeAndFlush(req).sync();

            // 7 等待通道关闭的异步任务结束
            // 服务监听通道会一直等待通道关闭的异步任务结束
            ChannelFuture closeFuture = channel.closeFuture();
            closeFuture.sync();

        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
package org.kayla.rpcfx.core.client.netty.client;

/**
 * @author Kayla(J - doIt)
 * @date 2021/11/25 23:39
 **/
public class ClientInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel sh) throws Exception {
        ChannelPipeline pipeline = sh.pipeline();
        pipeline.addLast(new HttpClientCodec());
        pipeline.addLast(new HttpObjectAggregator(65536));
        pipeline.addLast(new ClientInboundHandler());
        pipeline.addLast(new ClientOutboundHandler());

    }
}


@Slf4j
class ClientInboundHandler extends SimpleChannelInboundHandler<FullHttpResponse> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
        log.info("channelRead0");
        ByteBuf content = msg.content();
        int len = content.readableBytes();
        byte[] arr = new byte[len];
        content.getBytes(0, arr);
        log.info(new String(arr, "UTF-8"));
    }
}

@Slf4j
class ClientOutboundHandler extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        log.info("write");

        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            ByteBuf content = request.content();

            int len = content.readableBytes();
            byte[] arr = new byte[len];
            content.getBytes(0, arr);
            log.info(new String(arr, "UTF-8"));
        }

        super.write(ctx, msg, promise);
    }
}



http - Netty 5 sending JSON POST request - Stack Overflow

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Netty是一个基于NIO的网络编程框架,它可以帮助我们实现高性能、高可靠性的网络应用程序。在Netty中,我们可以使用HTTP客户端来发送HTTP请求。 下面是一个简单的Netty发送HTTP请求的示例: ```java import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequestEncoder; import io.netty.handler.codec.http.HttpResponseDecoder; import io.netty.handler.codec.http.HttpVersion; import java.net.URI; public class NettyHttpClient { private final String host; private final int port; public NettyHttpClient(String host, int port) { this.host = host; this.port = port; } public void sendGetRequest(String uri) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpResponseDecoder()); ch.pipeline().addLast(new HttpRequestEncoder()); } }); URI requestUri = new URI(uri); String path = requestUri.getRawPath(); String query = requestUri.getRawQuery(); if (query != null && !query.isEmpty()) { path = path + "?" + query; } DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); request.headers().set("Host", host); request.headers().set("Connection", "keep-alive"); request.headers().set("Accept", "*/*"); request.headers().set("User-Agent", "NettyHttpClient"); ChannelFuture future = bootstrap.connect(host, port).sync(); future.channel().write(request); future.channel().flush(); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } } ``` 在上面的示例中,我们创建了一个NettyHttpClient类,它接受主机名和端口号作为参数。然后,我们定义了一个sendGetRequest方法,该方法接受URI作为参数,并发送HTTP GET请求。 在sendGetRequest方法中,我们创建了一个NioEventLoopGroup,它处理所有事件,例如连接、读取和写入。然后,我们创建了一个Bootstrap对象,并设置了TCP_NODELAY选项和一个ChannelInitializer对象,该对象将添加一个HttpResponseDecoder和一个HttpRequestEncoder到管道中。 接下来,我们解析URI,并创建一个DefaultFullHttpRequest对象,该对象包含HTTP版本、HTTP方法、路径和头信息。最后,我们使用Bootstrap对象连接到主机并发送请求。 这是一个简单的Netty发送HTTP请求的示例,可以根据需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值