0

我正在使用以下类扩展输出流以了解我的上传进度。

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.entity.InputStreamEntity;

public class CountingInputStreamEntity extends InputStreamEntity {

    private UploadListener listener;
    private long length;

    public CountingInputStreamEntity(InputStream instream, long length) {
        super(instream, length);
        this.length = length;
    }

    public void setUploadListener(UploadListener listener) {
        this.listener = listener;
    }

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

    class CountingOutputStream extends OutputStream {
        private long counter = 0l;
        private OutputStream outputStream;

        public CountingOutputStream(OutputStream outputStream) {
            this.outputStream = outputStream;
        }

        @Override
        public void write(int oneByte) throws IOException {
            this.outputStream.write(oneByte);
            counter++;
            if (listener != null) {
                int percent = (int) ((counter * 100)/ length);
                listener.onChange(percent);
            }
        }
    }

    public interface UploadListener {
        public void onChange(int percent);
    }

}

调用类

final HttpResponse resp;
final HttpClient httpClient = new DefaultHttpClient();
final HttpPost post = new HttpPost(UPLOAD_URL);
ParcelFileDescriptor fileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r");
InputStream in = context.getContentResolver().openInputStream(uri);
CountingInputStreamEntity entity = new CountingInputStreamEntity(in, fileDescriptor.getStatSize());
entity.setListener(this);
post.setEntity(entity);
resp = httpClient.execute(post);

默认情况下,write 方法中的 len 变量返回 2048 个字节。有什么方法可以将 len 变量更改为自定义值。我希望 len 变量为 64kb 我怎样才能实现这一点,任何人都可以帮助我解决这个问题。

我可以增加写入服务器的字节数吗?

4

0 回答 0