【发布时间】: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();
}
}
}
}
我的文件已下载并具有与原始文件相同的字节数,但文件已损坏且校验和错误。
谁能告诉我怎么了?
【问题讨论】: