2012-05-13 32 views
0

我想用sonatype async http client-https://github.com/sonatype/async-http-client實現異步文件上傳進度。Java Sonatype異步HTTP客戶端上傳進度

我嘗試了文檔中建議的方法。使用傳輸監聽器。 http://sonatype.github.com/async-http-client/transfer-listener.html

我實現onBytesSent TransferListener接口(就像試驗):

public void onBytesSent(ByteBuffer byteBuffer) { 

    System.out.println("Total bytes sent - "); 
    System.out.println(byteBuffer.capacity()); 
} 
在另一個線程

然後(因爲我不希望阻止的應用程序),我試圖做到以下幾點:

TransferCompletionHandler tl = new TransferCompletionHandler(); 
tl.addTransferListener(listener); 

asyncHttpClient.preparePut(getFullUrl(fileWithPath)) 
     .setBody(new BodyGenerator() { 
      public Body createBody() throws IOException { 
       return new FileBodyWithOffset(file, offset); 
      } 
     }) 
     .addHeader(CONTENT_RANGE, new ContentRange(offset, localSize).toString()) 
     .execute(handler).get(); 

一切都很好。文件上傳正確,速度非常快。但問題是 - 我收到來自onBytesSent的消息,僅在TransferListener 之後上傳完成。例如,上傳在10分鐘內完成。在那10分鐘內,我什麼也得不到。只有在這之後,所有東西都印在控制檯上。

我不明白這段代碼有什麼問題。我只是試圖按照文檔。

我試圖在主線程中執行上面的代碼,它也沒有工作。

也許這是一個錯誤的方式來實現使用這個客戶端上傳進度監聽器?

回答

2

我會自己回答。我沒有設法解決與TransferListener的問題。所以我嘗試了另一種方式。

我已經把進度logick體內接口實現(讀法裏):

public class FileBodyWithOffset implements Body { 

    private final ReadableByteChannel channel; 

    private long actualOffset; 

    private final long contentLength; 

    public FileBodyWithOffset(final File file, final long offset) throws IOException { 

     final InputStream stream = new FileInputStream(file); 

     this.actualOffset = stream.skip(offset); 

     this.contentLength = file.length() - offset; 

     this.channel = Channels.newChannel(stream); 
    } 


    public long getContentLength() { 

     return this.contentLength; 
    } 

    public long read(ByteBuffer byteBuffer) throws IOException { 

     System.out.println(new Date()); 

     actualOffset += byteBuffer.capacity(); 

     return channel.read(byteBuffer); 
    } 

    public void close() throws IOException { 

     channel.close(); 
    } 

    public long getActualOffset() { 

     return actualOffset; 
    } 
} 

也許這是一個骯髒的把戲,但至少它的工作原理。