java - netty http 请求 getContent 有时会在正文中给出标题

标签 java http http-headers netty nio

我使用 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/

相关文章:

JAVA 连接到 COM 端口,问题,RXTX 库

java - Maven 无法通过强制身份验证从 HTTPS Nexus 下载 Artifact

java - 在java中创建可扩展枚举行为的最佳方法

http-headers - 内容安全策略 - 值得吗?

c++ - 如何从 QDateTime 生成 HTTP header If-Modified-Since 的时间戳?

用于替换通过 B 值链接的两个映射 Map<A,B>, Map<B,C> 的 Java 数据结构

http - 如何使用 WinHTTP 库进行 kerberos(windows 集成)身份验证

http - 使用 RemoteData 解码非 JSON 响应

http - 禁用网站之间的缓存共享

ruby - 将 HTTP 响应放入 Ruby on Rails 应用程序的哪个文件?