我正在使用ClientBootstrap在客户端模式下使用netty。当我试图收到一条消息大部分时间它工作正常并且只给我一个身体,但有时(服务器总是返回相同的响应)我在内容中得到一个标题,当我调用一个message.getContent():
Content-type: text/xml;charset=windows-1251
Content-length: 649
Connection: keep-alive
<?xml version="1.0" encoding="windows-1251"?>
<response>
<status>
<code>0</code>
</status>
<detail>
显然它应该只是http请求的主体。当它返回一个正文中的标题部分时,正文部分本身就是标题的大小。
这是我的PipileniFactory:
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
if (isSecure) {
SSLContext clientContext = SSLContext.getInstance("TLS");
clientContext.init(null, new TrustManager[]{DUMMY_TRUST_MANAGER}, null);
SSLEngine engine = clientContext.createSSLEngine();
engine.setUseClientMode(true);
pipeline.addLast("ssl", new SslHandler(engine));
}
pipeline.addLast("codec", new HttpClientCodec());
pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
pipeline.addLast("timeout", new ReadTimeoutHandler(timer, timeout, TimeUnit.MILLISECONDS));
pipeline.addLast("handler", ibConnectorHandler);
return pipeline;
}
这里是来自ibConnectorHandler的messageReceived:
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
logger.info("Received");
HttpResponse response = (HttpResponse) e.getMessage();
ChannelBuffer resContent = response.getContent();
byte[] content = null;
if (resContent.readable()) {
content = Arrays.copyOf(resContent.array(), resContent.readableBytes());
logger.debug(Arrays.toString(req.getParams().toArray()) + "----------" + new String(content));
}
}
我正在使用netty 3.5.8。
UPD 当一切正确时,resContent是instanceof org.jboss.netty.buffer.BigEndianHeapChannelBuffer。当它显示标题时resContent是instanceof org.jboss.netty.buffer.SlicedChannelBuffer。因此,当netty使用org.jboss.netty.buffer.SlicedChannelBuffer作为http消息内容时会出现问题。
答案 0 :(得分:2)
在“Arrays.copyOf(resContent.array(),resContent.readableBytes())”中,您不尊重数组中的偏移量。你还需要提交你可以从ChannelBuffer.arrayOffset()+ ChannelBuffer.readerIndex();
获得的偏移量。请参阅:http://static.netty.io/3.5/api/org/jboss/netty/buffer/ChannelBuffer.html#arrayOffset()