【问题标题】:Netty HTTP client download zip fileNetty HTTP 客户端下载 zip 文件
【发布时间】:2014-02-05 05:38:41
【问题描述】:

我正在编写 Netty 客户端,它使用一个特定的 URL (https://myserver.com/aaa.zip) 通过 HTTPS 从一台特定的服务器下载一个特定的大文件并将其保存在磁盘上。

我还没有找到任何 HTTP 客户端获取二进制响应的示例,所以挖掘了一些文档,这就是我得到的:

我使用的是 Netty 4.0.15

ChannelPipeline pipeline = socketChannel.pipeline();
    SSLEngine engine =
            SecureSslContextFactory.getClientContext().createSSLEngine();
        engine.setUseClientMode(true);

    pipeline.addLast("ssl", new SslHandler(engine));
    pipeline.addLast("codec",new HttpClientCodec());
    pipeline.addLast("handler", new HttpWebClientHandler());

我的 Handler 看起来像这样:

public class HttpWebClientHandler extends SimpleChannelInboundHandler<HttpObject> {

    File file = new File("aaa.zip");
        int written = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
            throws Exception {

        if (msg instanceof HttpContent){
            HttpContent content = (HttpContent) msg;
            int currentlyWritten = 0;
            ByteBuf byteBuf = content.content();        
             FileOutputStream outputStream = new FileOutputStream(file);
             FileChannel localfileChannel = outputStream.getChannel();
             try{
             ByteBuffer byteBuffer = byteBuf.nioBuffer();
             currentlyWritten += localfileChannel.write(byteBuffer,written);
             written+=currentlyWritten;
                byteBuf.readerIndex(byteBuf.readerIndex() + currentlyWritten);
                localfileChannel.force(false);
            }finally{
                localfileChannel.close();
                outputStream.close();
            }
        }
    }
}

我的文件已下载并具有与原始文件相同的字节数,但文件已损坏且校验和错误。

谁能告诉我怎么了?

【问题讨论】:

    标签: netty nio


    【解决方案1】:

    HttpObjectDecoder 可能会为单个 HTTP 响应生成多个 HttpContent。您在每个 HttpContent 上创建一个新的 FileOutputStream,因此文件中只有响应的最后一部分。

    解决问题:

    • HttpRequest 上打开文件
    • 写所有HttpContents的内容
    • 关闭LastHttpContent上的文件。

    【讨论】:

      猜你喜欢
      • 2014-10-10
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2016-10-23
      • 2019-07-08
      • 1970-01-01
      • 2021-12-05
      • 2016-03-20
      相关资源
      最近更新 更多