Android Apache - 上传并跟踪进度
问题描述:
我正在尝试使用https +帖子上传图片,并跟踪其进度。Android Apache - 上传并跟踪进度
StringEntity strEntity = null;
int totalSize = 0;
try
{
strEntity = new StringEntity(jsonBody.toString(), HTTP.UTF_8);
strEntity.setContentEncoding(HTTP.UTF_8);
strEntity.setContentType("application/json");
totalSize = jsonBody.toString().getBytes().length;
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
ProgressHttpEntityWrapper httpEntity = new ProgressHttpEntityWrapper(strEntity, progressCallback, totalSize);
httpPost.setEntity(httpEntity);
我发现这里是我的类扩展HttpEntityWrapper
public class ProgressHttpEntityWrapper extends HttpEntityWrapper
{
private final ProgressCallback progressCallback;
private final long fileSize;
public ProgressHttpEntityWrapper(final HttpEntity entity, final ProgressCallback progressCallback, int fileSize)
{
super(entity);
this.progressCallback = progressCallback;
this.fileSize = fileSize;
Log.e("AsyncUploadData", "Constructor");
}
@Override
public void writeTo(final OutputStream out) throws IOException
{
Log.e("AsyncUploadData", "writeTo: " +getContentLength());
super.writeTo(out instanceof ProgressFilterOutputStream ? out
: new ProgressFilterOutputStream(out, this.progressCallback, this.fileSize));
}
.....
}
然而,我发现我的 “的writeTo” 方法总是被调用两次。 我想不通为什么!请帮忙!
是否有可能与我的服务器有关? 感谢您的帮助!
答
您的writeTo()
方法正在调用this.wrappedEntity.writeTo()
,我认为这是多余的。
我用这样的一个时间:
@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);
}
}
所有学分转到:http://toolongdidntread.com/android/android-multipart-post-with-progress-bar/
+0
我改为“super.writeTo(...)”,但它仍然被调用两次:(...任何建议? – user2967370 2014-11-04 10:42:26
你可以试试http://delimitry.blogspot.in/2011/08/android-upload-progress .html – 2014-11-04 09:56:13