2012-10-10 49 views
1

我在使用ClientBootstrap的客户端模式下使用netty。当我试图接收邮件大多数时候它工作正常,并返回我只有一个机构,但有时(服务器总是返回相同的响应)当我打电话message.getContent()内容时,我得到一个标题:netty http请求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)); 
    } 

} 

我使用网状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消息的内容时会出现问题。

回答

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()

+0

是的,谢谢,这是问题。我完成使用resContent.getBytes尊重抵消。 顺便说一下,这段代码在netty 3.5.1中工作正常 – Aldarund

+0

它在3.5.1中工作正常,因为我们做了一些优化,它可以保护你的某些字节拷贝,从而加快速度。在3.5.1中,我们总是为内容创建一个新的缓冲区并将其复制。 –