过去开发使用HttpClient上传文件可以使用CountingHttpEntity(multipartEntity, listener)方法得到上传进度。由于现在开发使用okhttp,但是貌似okhttp没有提供监听上传文件进度的方法。
使用HttpClient时,监听上传进度可以使用下面的方法
HttpPost httppost = HttpPost(url)
File file = File(path)ContentBody
contentBody=FileBody(file)
MultipartEntity multipartEntity=MultipartEntity()
multipartEntity.addPart(typecontentBody)CountingHttpEntity
entity = CountingHttpEntity(multipartEntity)
httppost.setEntity(entity)
在Okhttp中貌似没有发现类似的方法。看看一Okhttp创建RequestBody的方法。
/** Returns a new request body that transmits the content of {@code file}. */
public static RequestBody create(final @Nullable MediaType contentType, final File file) {
if (file == null) throw new NullPointerException("file == null");
return new RequestBody() {
@Override public @Nullable MediaType contentType() {
return contentType;
}
@Override public long contentLength() {
return file.length();
}
@Override public void writeTo(BufferedSink sink) throws IOException {
Source source = null;
try {
source = Okio.source(file);
sink.writeAll(source);
} finally {
Util.closeQuietly(source);
}
}
};
}
}
那么可以通过自定义类实现监听上传文件进度具体实现方法请参考道客优--OkHttp上传文件,监听上传进度