我正在编写 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/