2011-03-16 56 views
0

我只是在學習,所以我需要你的建議。我找到了演示HttpClient進度監聽器的代碼示例。這是好的,但我不知道如何實現ProgressListener接口(看這個代碼...)與我的代碼,因爲ProgressListener接口是一個內部接口,但我的HttpClient代碼是在另一個類:(請告訴我的示例技巧。驗證碼:HttpClient和ProgressListener - 幫助實現

import java.io.FilterOutputStream; 
import java.io.IOException; 
import java.io.OutputStream; 
import java.nio.charset.Charset; 
import org.apache.http.entity.mime.HttpMultipartMode; 
import org.apache.http.entity.mime.MultipartEntity; 

public class CountingMultipartEntity extends MultipartEntity { 

private final ProgressListener listener; 

public CountingMultipartEntity(final ProgressListener listener) { 
    super(); 
    this.listener = listener; 
} 

public CountingMultipartEntity(final HttpMultipartMode mode, final ProgressListener listener) { 
    super(mode); 
    this.listener = listener; 
} 

public CountingMultipartEntity(HttpMultipartMode mode, final String boundary, 
     final Charset charset, final ProgressListener listener) { 
    super(mode, boundary, charset); 
    this.listener = listener; 
} 

@Override 
public void writeTo(final OutputStream outstream) throws IOException { 
    super.writeTo(new CountingOutputStream(outstream, this.listener)); 
} 

public static interface ProgressListener { 
    void transferred(long num); 
} 

public static class CountingOutputStream extends FilterOutputStream { 

    private final ProgressListener listener; 
    private long transferred; 

    public CountingOutputStream(final OutputStream out, 
      final ProgressListener listener) { 
     super(out); 
     this.listener = listener; 
     this.transferred = 0; 
    } 


    public void write(byte[] b, int off, int len) throws IOException { 
     out.write(b, off, len); 
     this.transferred += len; 
     this.listener.transferred(this.transferred); 
    } 

    public void write(int b) throws IOException { 
     out.write(b); 
     this.transferred++; 
     this.listener.transferred(this.transferred); 
    } 
} 

}

非常感謝任何有用的信息

安德魯

回答

2

你可以簡單地說

。 0
class MyProgressListener implements CountingMultipartEntity.ProgressListener { 
    public void transferred(long num) { 
     System.out.println(num + " bytes transferred so far..."); //Display Progress 
    } 
} 

然後

new CountingMultipartEntity(new MyProgressListener()); 

(編輯,以提供細節和固定低級錯誤)

+0

爲什麼HttpClient的。 ? – user592704 2011-03-16 05:13:15

+0

請顯示更詳細的摘錄:( – user592704 2011-03-16 05:15:21

+0

謝謝,但我不明白...爲什麼你想用這個片段說HttpClient.ProgressListener?因爲演示類的名字是CountingMultipartEntity,不是嗎?什麼HttpClient。 (...)用於? – user592704 2011-03-16 05:22:44