我看了看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);
        }
    }
}




我可以实现这样的接口吗?

...
public static interface ProgressListener {
        void transferred(long num);
    }
    public static class Progress implements ProgressListener
    {

      public void transferred(long num) {
//            // update the progress bar or whatever else you might want to do

        }

    }
...


但是,如何针对包含HttpClient的外部类初始化ProgressListener呢?

CountingMultiPartEntity entity = new CountingMultiPartEntity(new ProgressListener() {

        public void transferred(long num) {
            // update the progress bar or whatever else you might want to do
        }
    });

最佳答案

如果还没有实现ProgressListener接口的类,则需要自己构造一个实现。对于诸如侦听器之类的事情,通常使用匿名内部类来完成。

CountingMultipartEntity entity = new CountingMultipartEntity(new ProgressListener() {
    @Override
    public void transferred(long num) {
        // update the progress bar or whatever else you might want to do
    }
});

09-08 06:17