Netty HTTP客户端下载zip文件

标签 netty nio

我正在编写 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());

我的处理程序如下所示:

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

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

谁能告诉我出了什么问题吗?

最佳答案

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

解决问题:

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

关于Netty HTTP客户端下载zip文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21342835/

相关文章:

netty - 为 Netty 服务器上的 Spring Reactive Web 应用程序定义最大并发用户数

java - 如何销毁SelectionKey附件?附加(空)不起作用

java - 在没有 O_SYNC 语义的情况下用 Java 编写文件

Java NIO 非阻塞模式 vs node.js 异步操作

java - 发送到 ServerHandler 外部时,客户端未收到服务器发送的消息

java - 用于连接超时和打开连接数的 Netty channel 配置

java - Netty客户端只能接收服务器的一次响应

Java NIO select() 返回时没有选择键 - 为什么?

java - 如何获取 Windows 负载值

java - 如何在 Play 中将所有入站请求转换为 UTF-8!框架