【问题标题】:DefaultHttpContent instead of HttpResponse in netty 4.0.23netty 4.0.23 中的 DefaultHttpContent 而不是 HttpResponse
【发布时间】:2015-10-29 02:11:14
【问题描述】:

我有以下用于 Http 客户端的管道配置 -

pipeline.addLast("ssl", new SslHandler());      
pipeline.addLast("decoder", new HttpResponseDecoder());     
pipeline.addLast("encoder", new HttpRequestEncoder());
pipeline.addLast("handler", new MySimpleChannelInboundHandler());

MySimpleChannelInboundHandlerchannelRead0() 方法中,我得到了DefaultHttpContent 的实例,而不是HttpResponse。当我使用 -

记录DefaultHttpContent 的内容时
DefaultHttpContent content = (DefaultHttpContent) msg;          
LOG.debug(content.content().toString(CharsetUtil.UTF_8));

我可以看到正在记录的实际 HTTP 响应。

为什么即使我在管道中有一个 HTTP 解码器,这个 HTTP 响应也没有被解码为 HttpResponse 对象?

谢谢!

【问题讨论】:

    标签: netty


    【解决方案1】:

    在 enc/decoders 之前使用 HttpObjectAggregator 以聚合 httpResponse 和所有以下 HttpContents。在管道中添加HttpObjectAggregator 后,您将在处理程序中获得FullHttpResponse 对象。

    例如:p.addLast("aggregator", new HttpObjectAggregator(1048576));

    还有一件事,如果您没有为客户端实现自己的编码/解码器,您可以使用 netty 提供的HttpClientCodec

    【讨论】:

    • 感谢您的回复。我知道在HttpDecoder 之后在我的管道中使用HttpObjectAggregator 将导致FullHttpResponse。但我的问题是——没有HttpObjectAggregator,我应该得到一个HttpResponse、0 到n HttpContent 和一个LastHttpContent。但我只得到一个DefaultHttpContent(它有正确的响应)。我尝试在解码器之后添加一个HttpObjectAggregator,我在聚合器的channelRead0() 上得到了一个NullPointerException。另外,我不能使用HttpClientCodec,因为我正在修改使用 enc/dec 的现有库。
    【解决方案2】:

    我遇到了问题。 HttpResponseDecoder 之前已经解码了对 HTTP CONNECT 请求的响应。我没有重写 isContentAlwaysEmpty(HttpMessage httpMessage) 方法来为 CONNECT 请求返回 false。这使HttpResponseDecoder 处于不良状态。它期待响应中的内容,但对 HTTP CONNECT 的响应没有。当下一个请求的响应到达时,它被当作内容,而不是解码成HttpResponse

    我扩展了HttpResponseDecoder 并覆盖(覆盖?)isContentAlwaysEmpty(HttpMessage httpMessage) 为 CONNECT 请求返回 false 并且它有效。这在“解码 CONNECT 请求的响应”下的 HttpResponseDecoderclass level documentation 中有记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 1970-01-01
      相关资源
      最近更新 更多