Netty 舍弃 Http Response

morethink
  • 181

使用Netty作为Http Client 发送请求,添加如下Handler

pipeline.addLast(new HttpClientCodec());
pipeline.addLast(new HttpObjectAggregator(10 * 1024));

现在发现当返回体很大的时候,会触发 TooLongFrameException
请问如何在连接不断开的情况在HttpClientCodecHttpObjectAggregator中间加一个HttpDiscardHandler,发现Content-length大于10 * 1024时就舍弃得到的Http Response

回复
阅读 1.4k
1 个回答
public class HttpDiscardHandler extends ChannelInboundHandlerAdapter {
    
        private boolean ignore = false;
    
        private int maxContentLength = 9 * 1024;
    
        private String body = "返回体超过" + maxContentLength + "B,已省略";
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("success!~!~");
            if (msg instanceof HttpResponse) {
                HttpResponse response = (HttpResponse) msg;
                if (Integer.valueOf(response.headers().get("Content-Length")) > maxContentLength) {
                    msg = new DefaultFullHttpResponse(response.protocolVersion(), response.status(), Unpooled.copiedBuffer(body, CharsetUtil.UTF_8));
                    ignore = true;
                }   else {
                ignore = false;
            }
                ctx.fireChannelRead(msg);
            } else {
                if (ignore) {
                    ReferenceCountUtil.release(msg);
                } else {
                    ctx.fireChannelRead(msg);
                }
            }
        }
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏