开发者

HttpClient and ProgressListener - help to implement

I am just studying so I need your advice. I have found a code example which demos HttpClient progress listener. It is good but I have no idea how to implement ProgressListener interface (watch this code...) with my code because ProgressListener interface is an inner interface but my HttpClient code is in another class :( Please advise me the example tips. Here is the code:

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.开发者_StackOverflow社区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);
    }
}

}

Much appreciated any useful information.

Andrew


You can simply say

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

and then

new CountingMultipartEntity(new MyProgressListener());

(edited to provide even more detail and fix stupid mistake)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜