Last active
July 5, 2016 05:40
-
-
Save ashmeh6/53a16054c4ebe560373657e65f8f7c2f to your computer and use it in GitHub Desktop.
Can be used as HttpPost data with upload percentage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by Ashish on 09-Jun-16. | |
*/ | |
/** | |
* Required Library httpmime-4.1-beta1.jar | |
* | |
* Example of use | |
* | |
* doInBackground(Params...){ | |
.... | |
final CustomMultiPartEntity reqEntity = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, new CustomMultiPartEntity.ProgressListener() { | |
@Override | |
public void transferred(long num) { | |
int percentage = (int) ((num * 100)/total); | |
publishProgress(percentage); | |
} | |
}); | |
} | |
*/ | |
import org.apache.http.entity.mime.HttpMultipartMode; | |
import org.apache.http.entity.mime.MultipartEntity; | |
import java.io.FilterOutputStream; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import java.nio.charset.Charset; | |
public class CustomMultiPartEntity extends MultipartEntity { | |
private final ProgressListener listener; | |
public CustomMultiPartEntity(final ProgressListener listener) { | |
super(); | |
this.listener = listener; | |
} | |
public CustomMultiPartEntity(final HttpMultipartMode mode, final ProgressListener listener) { | |
super(mode); | |
this.listener = listener; | |
} | |
public CustomMultiPartEntity(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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment