AndroidHttpClientにProgressDialogを実装したい。ここで、 CountingMultipartEntityの簡単な実装を見つけました。
さらに、コンテンツの長さのサポートを追加しました。メソッドをオーバーライドします。
FileBodyのアップロードはほぼ正常に機能します。アップロードに1つのファイルが含まれている場合は完全に機能しますが、2つのファイルがある場合は、2番目のファイルは部分的にしかアップロードされません。InputStreamBodyは機能しますが、 InputStream
の長さをカウントしない場合に限ります。だから私はそれをリセットする必要がありますが、どうやって?addPart
ここで私のオーバーライドaddPart
:
@Override
public void addPart(String name, ContentBody cb) {
if (cb instanceof FileBody) {
this.contentLength += ((FileBody) cb).getFile().length();
} else if (cb instanceof InputStreamBody) {
try {
CountingInputStream in =
new CountingInputStream(((InputStreamBody) cb).getInputStream());
ObjectInputStream ois = new ObjectInputStream(in);
ois.readObject();
this.contentLength += in.getBytesRead();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
super.addPart(name, cb);
}
CountingInputStreamは、InputStreamの単純な拡張です。
public class CountingInputStream extends InputStream {
private InputStream source;
private long bytesRead = 0;
public CountingInputStream(InputStream source) {
this.source = source;
}
public int read() throws IOException {
int value = source.read();
bytesRead++;
return value;
}
public long getBytesRead() {
return bytesRead;
}
}
カウントはほぼ機能します。2バイトしかないので、そこにあるべきではありません。しかし、それはとても重要です。
まず、ストリームをリセットする必要があると思いました。後に呼び出されるリセットは、 IOExceptionin.getReadedBytes();
につながります。
アドバイスありがとうございます。