59 lines
1.7 KiB
Java
Raw Normal View History

2019-04-29 15:06:17 +03:00
package com.baeldung.httpclient;
2014-12-21 23:24:46 +02:00
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
public class ProgressEntityWrapper extends HttpEntityWrapper {
private final ProgressListener listener;
2017-07-19 11:16:44 +03:00
ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) {
2014-12-21 23:24:46 +02:00
super(entity);
this.listener = listener;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new CountingOutputStream(outstream, listener, getContentLength()));
}
2017-07-19 11:16:44 +03:00
public interface ProgressListener {
2014-12-21 23:24:46 +02:00
void progress(float percentage);
}
public static class CountingOutputStream extends FilterOutputStream {
private final ProgressListener listener;
private long transferred;
private long totalBytes;
2017-07-19 11:16:44 +03:00
CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) {
2014-12-21 23:24:46 +02:00
super(out);
this.listener = listener;
transferred = 0;
this.totalBytes = totalBytes;
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
out.write(b, off, len);
transferred += len;
listener.progress(getCurrentProgress());
}
@Override
public void write(final int b) throws IOException {
out.write(b);
transferred++;
listener.progress(getCurrentProgress());
}
private float getCurrentProgress() {
return ((float) transferred / totalBytes) * 100;
}
}
}