XiMengJianYu/.svn/pristine/c4/c4933237649bc0726e53874879ac20dec87b0992.svn-base
2023-04-17 17:58:44 +08:00

78 lines
2.3 KiB
Plaintext
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.cm.utils.net.body;
import com.cm.utils.net.response.ResponseHandler;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;
/**
* Created by Xuer on 2017/3/8.
* 重写request body 设置上传进度监听
*/
public class ProgressRequestBody extends RequestBody {
private ResponseHandler mResponseHandler; //回调监听
private RequestBody mRequestBody;
private BufferedSink mBufferedSink;
public ProgressRequestBody(RequestBody requestBody, ResponseHandler responseHandler) {
this.mResponseHandler = responseHandler;
this.mRequestBody = requestBody;
}
@Override
public MediaType contentType() {
return mRequestBody.contentType();
}
@Override
public long contentLength() throws IOException {
return mRequestBody.contentLength();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
if(mBufferedSink == null) {
mBufferedSink = Okio.buffer(sink(sink));
}
//写入
mRequestBody.writeTo(mBufferedSink);
//必须调用flush否则最后一部分数据可能不会被写入
mBufferedSink.flush();
}
/**
* 写入,回调进度接口
* @param sink Sink
* @return Sink
*/
private Sink sink(Sink sink) {
return new ForwardingSink(sink) {
//当前写入字节数
long bytesWritten = 0L;
//总字节长度避免多次调用contentLength()方法
long contentLength = 0L;
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
if (contentLength == 0) {
//获得contentLength的值后续不再调用
contentLength = contentLength();
}
//增加当前写入的字节数
bytesWritten += byteCount;
//回调
mResponseHandler.onProgress(bytesWritten, contentLength);
}
};
}
}