【问题标题】:How to Read the message Body in a HTTP POST in Netty (version >= 4.x)如何在 Netty 中读取 HTTP POST 中的消息正文(版本 >= 4.x)
【发布时间】:2015-05-06 07:34:55
【问题描述】:

在我的服务器处理程序中; - channelRead() 总是将消息作为 HTTPRequest 获取,并且我找不到任何地方来获取 POST 请求有效负载。

  • 然后我尝试在我的处理程序中执行以下操作以检查它是否有效。解码器有 0 个元素。

HttpPostRequestDecoder 解码器 = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request);

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

【问题讨论】:

  • 能否请您添加管道的完整配置?
  • @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("解码器", new HttpRequestDecoder()); pipeline.addLast("编码器", new HttpResponseEncoder()); pipeline.addLast("handler", new MyServerHandler()); }

标签: http netty nio


【解决方案1】:

您的 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());

或者,您可以检查this example,其中HttpRequestHttpContent 分别处理。

【讨论】:

    【解决方案2】:

    正如 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-25
      • 2019-11-30
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多