我正在尝试使用https + post上传图片,并跟踪其进度。
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”方法总是被调用两次。 我弄清楚为什么!!请帮忙!
是否有可能与我的服务器有关? 谢谢你的帮助!!
答案 0 :(得分:0)
您的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/