2014-01-24 460 views
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的,但文件已損壞,有校驗和錯誤。

有人可以告訴我什麼是錯的?

回答

2

HttpObjectDecoder對於單個HTTP響應可能會產生多個HttpContent。您在每個HttpContent上創建一個新的FileOutputStream,因此您將只有文件中的最後一部分響應。

要解決該問題:

  • 公開賽HttpRequest
  • 文件寫入的所有HttpContent小號
  • 內容合上LastHttpContent文件。
+0

你可以發表完整的工作代碼嗎? – thangamanikasi

+0

請詳細說明 –