我使用 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 请求的主体。当它在主体中返回 header 部分时,主体部分本身会被 header 的大小截断。
这是我的 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 收到的消息:
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。
更新 当一切正确时,resContent 是 instanceof org.jboss.netty.buffer.BigEndianHeapChannelBuffer。当它显示标题 resContent 是 instanceof org.jboss.netty.buffer.SlicedChannelBuffer 时。因此,当 netty 使用 org.jboss.netty.buffer.SlicedChannelBuffer 作为 http 消息的内容时,就会出现问题。
最佳答案
在“Arrays.copyOf(resContent.array(), resContent.readableBytes())”中,您不考虑数组中的偏移量。您还需要提交可以从 ChannelBuffer.arrayOffset() + ChannelBuffer.readerIndex(); 获得的偏移量;
参见:http://static.netty.io/3.5/api/org/jboss/netty/buffer/ChannelBuffer.html#arrayOffset ()
关于java - netty http 请求 getContent 有时会在正文中给出标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12821798/