我正在编写Netty客户端,它通过HTTPS使用一个特定网址(https://myserver.com/aaa.zip
)从一个特定服务器下载一个特定的大文件并将其保存在磁盘上。
我还没有找到任何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();
}
}
}
}
我的文件已下载并且与原始文件具有相同的字节数,但文件已损坏且校验和错误。
有人可以告诉我出了什么问题吗?
答案 0 :(得分:2)
HttpObjectDecoder
可能会为单个HTTP响应生成多个HttpContent
。您在每个FileOutputStream
上创建一个新的HttpContent
,因此您只会在文件中包含响应的最后一部分。
解决问题:
HttpRequest
HttpContent
s LastHttpContent
上的文件。