Netty HTTP客户端下载zip文件
我正在编写Netty客户端,它使用一个特定的url(Netty HTTP客户端下载zip文件,netty,nio,Netty,Nio,我正在编写Netty客户端,它使用一个特定的url(https://myserver.com/aaa.zip)并将其保存在磁盘上 我还没有找到任何HTTP客户端获得二进制响应的示例,因此,挖掘一些文档就是我得到的: 我用的是Netty 4.0.15 ChannelPipeline pipeline = socketChannel.pipeline(); SSLEngine engine = SecureSslContextFactory.getClientCont
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();
}
}
}
}
公共类HttpWebClientHandler扩展了SimpleChannelInboundHandler{
File File=新文件(“aaa.zip”);
int-writed=0;
@凌驾
受保护的无效channelRead0(ChannelHandlerContext ctx、HttpObject msg)
抛出异常{
if(HttpContent的消息实例){
HttpContent=(HttpContent)msg;
int currentlywrited=0;
ByteBuf ByteBuf=content.content();
FileOutputStream outputStream=新的FileOutputStream(文件);
FileChannel localfileChannel=outputStream.getChannel();
试一试{
ByteBuffer ByteBuffer=byteBuf.nioBuffer();
currentlywrited+=localfileChannel.write(byteBuffer,writed);
写入+=当前写入;
byteBuf.readerIndex(byteBuf.readerIndex()+当前写入);
localfileChannel.force(false);
}最后{
localfileChannel.close();
outputStream.close();
}
}
}
}
我的文件已下载,字节数与原始文件相同,但文件已损坏,校验和错误
有谁能告诉我出了什么问题吗?
HttpObjectDecoder
可能会为单个HTTP响应生成多个HttpContent
。在每个HttpContent
上创建一个新的FileOutputStream
,因此文件中只有响应的最后一部分
要解决此问题,请执行以下操作:
- 在
HttpRequest
- 编写所有
s的内容HttpContent
- 在
上关闭文件LastHttpContent