获取Netty中为gzip chunked响应接收的字节数

时间:2016-03-30 22:08:11

标签: java http netty chunked-encoding

我正在尝试解决说明中的问题。目前我有这个管道:

p.addLast(sslCtx.newHandler(ch.alloc()));
p.addLast(new HttpClientCodec());
p.addLast(new MyCustomHttpContentDecompressor());
// p.addLast(new HttpObjectAggregator(1048576));
p.addLast(businessLogicHandler);

当服务器返回非分块响应时,它包含Content-Length标头。我成功地在我的自定义HttpContentDecompressor中检索此值,就在它删除此标头并执行gzip解压缩之前。

但是当服务器决定发送分块响应时,我运气不好,因为没有Content-Length标头。我尝试了HttpObjectAggregator,但似乎它返回了解压缩的字节数。我还审查了netty traffic包,但它解决了不同的任务。

我觉得解决方案很简单,但我不太了解netty。也许有一种方法可以向管道添加一个处理程序(例如在解压缩程序之前),它将读取缓冲区中的所有字节,保存数字并将它们进一步传递给管道?一些代码示例将非常有用。

1 个答案:

答案 0 :(得分:0)

解决方案:

public class TrafficInterceptorHandler extends ChannelInboundHandlerAdapter {

    public static final String NAME = "trafficInterceptor";
    private static Logger LOG = LoggerFactory.getLogger(TrafficInterceptorHandler.class);

    private AtomicInteger readBytes = new AtomicInteger(0);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf) {
            ByteBuf byteBuf = (ByteBuf) msg;
            readBytes.addAndGet(byteBuf.readableBytes());
        } else {
            LOG.warn("Received msg is not a ByteBuffer. Actual class: " + msg.getClass());
        }
        ctx.fireChannelRead(msg);
    }
    public int getReadBytes() {
        return readBytes.get();
    }
}

应该在其他处理程序之前添加到管道

p.addLast(TrafficInterceptorHandler.NAME, new TrafficInterceptorHandler());
p.addLast(sslCtx.newHandler(ch.alloc()));
p.addLast(new HttpClientCodec());
...