如何在Netty中的HTTP POST中读取消息Body(版本> = 4.x)

Sub*_*nga 2 nio http netty

在我的服务器处理器; - channelRead()总是将msg作为HTTPRequest获取,在那里我找不到任何获取POST请求有效负载的地方.

  • 然后我尝试在我的处理程序中检查它是否有效.解码器有0个元素.

HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false),request);

在我的服务器管道中,我只有HttpServerCodec和自定义处理程序.

Leo*_*mes 6

您的HTTP请求可能会被分块.您应该尝试io.netty.handler.codec.http.HttpObjectAggregator在编解码器之后添加到您的管道.它将为您的处理程序提供FullHttpRequest.

 ChannelPipeline p = ...;
 ...
 p.addLast("encoder", new HttpResponseEncoder());
 p.addLast("decoder", new HttpRequestDecoder());
 p.addLast("aggregator", new HttpObjectAggregator(1048576));
 ...
 p.addLast("handler", new MyServerHandler());
Run Code Online (Sandbox Code Playgroud)

或者,您可以检查此示例在哪里HttpRequestHttpContent单独处理.


小智 5

正如 Leo Gomes 提到的,HTTP 请求可能是分块的。所以在管道中你自己的处理程序之前添加 HttpObjectAggregator 。如果 HTTP POST 请求正文是简单的 Json 字符串。您可以在自己的处理程序中解析它,如下所示:

    private String parseJosnRequest(FullHttpRequest request){
    ByteBuf jsonBuf = request.content();
    String jsonStr = jsonBuf.toString(CharsetUtil.UTF_8);
    return jsonStr;
}
Run Code Online (Sandbox Code Playgroud)