过去开发使用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); } } }; } }
那么可以通过自定义类实现监听上传文件进度
public class ProgressBody extends RequestBody { public interface ProgressListener { void transferred( long cur,long total ); } public static final int SEGMENT_SIZE = 4*1024; // okio.Segment.SIZE protected File file; protected ProgressListener listener; protected String contentType; public ProgressBody(File file, String contentType, ProgressListener listener) { this.file = file; this.contentType = contentType; this.listener = listener; } protected ProgressBody() {} @Override public long contentLength() { return file.length(); } @Override public MediaType contentType() { return MediaType.parse(contentType); } @Override public void writeTo(BufferedSink sink) throws IOException { Source source = null; try { source = Okio.source(file); long total = 0; long read; while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) { total += read; sink.flush(); this.listener.transferred(total,contentLength()); } } finally { Util.closeQuietly(source); } } }
哈哈,至此可以实现上传文件进度监听了。