在netty 4中记录http请求

在netty 4中记录http请求,netty,Netty,我正在构建一个netty代理服务器来查询Opentsdb,类似这样: 它很好用。但出于调试目的,我添加了一段代码来记录接收和发送的http请求,问题是当我这样做时,Opentsdb不会将响应发送给我 我添加的代码和原始代码是这样的(我将添加的代码提取为一个名为logMessage的方法)(此代码也不起作用): 公共类NettyProxyServerHandler扩展ChannelInboundHandlerAdapter{ 私有字符串remoteHost=“192.168.235.138”; 专

我正在构建一个netty代理服务器来查询Opentsdb,类似这样:

它很好用。但出于调试目的,我添加了一段代码来记录接收和发送的http请求,问题是当我这样做时,Opentsdb不会将响应发送给我

我添加的代码和原始代码是这样的(我将添加的代码提取为一个名为logMessage的方法)(此代码也不起作用):

公共类NettyProxyServerHandler扩展ChannelInboundHandlerAdapter{
私有字符串remoteHost=“192.168.235.138”;
专用int远程端口=4399;
专用通道外部通道;
公共NettyProxyServerHandler(){
超级();
}
公共NettyProxyServerHandler(字符串remoteHost,int remotePort){
超级();
this.remoteHost=remoteHost;
this.remotePort=remotePort;
}
@凌驾
public void channelRead(final ChannelHandlerContext ctx,final Object msg)引发异常{
if(outBoundChannel==null | |!ctx.channel().isActive()){
/* 创建内蒂客户,连接到远程地址 */
Bootstrap Bootstrap=新的Bootstrap();
bootstrap.group(ctx.channel().eventLoop())
.channel(ctx.channel().getClass())
.handler(新的通道初始值设定项(){
@凌驾
受保护信道(SocketChannel ch)
抛出异常{
ChannelPipeline=通道管道();
addLast(“codec”,新的HttpClientCodec());
pipeline.addLast(“聚合器”,新的HttpObjectAggregator(1048576));
addLast(新的NettyProxyClientHandler(ctx.channel());
}});
ChannelFuture=bootstrap.connect(远程主机、远程端口);
outBoundChannel=future.channel();
/*渠道建立成功后,将请求发送给远程主机 */
future.addListener(新的ChannelFutureListener(){
@凌驾
public void operation complete(ChannelFuture future)引发异常{
if(future.issucess()){
//这是我补充的
logMessage((FullHttpRequest)消息);
future.channel().writeAndFlush(msg);
}否则{
future.channel().close();
}
}
});
}否则{
//这是我补充的
logMessage((FullHttpRequest)消息);
outBoundChannel.writeAndFlush(msg);
}
}
//我添加了这个方法。
私有无效日志消息(FullHttpRequest消息){
ByteBuf m=msg.content();
StringBuilder sb=新的StringBuilder();
while(m.isReadable()){
sb.append((char)m.readByte());
}
字符串内容=sb.toString();
StringBuilder sblog=新的StringBuilder();
sblog.append(“msg:\n”).append(msg.getMethod()+“”+msg.getUri()+“”+msg.getProtocolVersion()+“\n”);
对于(Map.Entry:msg.headers().entries()){
sblog.append(entry.getKey()+”:“+entry.getValue()+”\n”);
}
sblog.append(“\n”).append(内容);
System.out.println(sblog.toString());
}

知道为什么以及什么是在netty中记录http请求和响应的正确方法吗?

发现了问题所在。我在logMessage方法中使用了readByte()方法,这将更改消息字节的readerIndex,这意味着消息的实际内容会减少。如果改用ByteBuf.toString(字符集)(此方法不会更改readerIndex),我得到服务器响应,如下所示:

String content = null;
    if(msg.content().isReadable()) {
        content = msg.content().toString(Charset.forName("UTF-8"));
    }
String content = null;
    if(msg.content().isReadable()) {
        content = msg.content().toString(Charset.forName("UTF-8"));
    }