2
我正在寫Netty客戶端,它通過HTTPS使用一個特定的URL(https://myserver.com/aaa.zip
)從一個特定的服務器下載一個特定的大文件,並將其保存在磁盤上。Netty HTTP客戶端下載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();
}
}
}
}
我的文件被下載,並有字節原來相同ammount的,但文件已損壞,有校驗和錯誤。
有人可以告訴我什麼是錯的?
你可以發表完整的工作代碼嗎? – thangamanikasi
請詳細說明 –