com.cmonbaby.http.stream.FileResponseBody Maven / Gradle / Ivy
Show all versions of http_lower Show documentation
package com.cmonbaby.http.stream;
import androidx.annotation.NonNull;
import com.cmonbaby.http.stream.listener.ProgressListener;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;
/**
* Author: Simon
*
QO: 8950764
*
Email: [email protected]
*
WebSize: https://www.cmonbaby.com
*
Version: 1.0.0
*
Date: 2020/12/28
*
Description: 扩展OkHttp的请求体,实现下载时的进度提示
*/
public final class FileResponseBody extends ResponseBody {
/**
* 实际请求体
*/
private final ResponseBody mResponseBody;
/**
* 下载回调接口
*/
private final ProgressListener progressListener;
/**
* 包装完成的BufferedSource
*/
private BufferedSource mBufferedSource;
/**
* 构造函数,赋值
*
* @param responseBody 待包装的响应体
* @param progressListener 回调接口
*/
public FileResponseBody(ResponseBody responseBody, ProgressListener progressListener) {
this.mResponseBody = responseBody;
this.progressListener = progressListener;
}
/**
* 重写进行包装source
*
* @return BufferedSource
*/
@NonNull
@Override
public BufferedSource source() {
if (mBufferedSource == null) {
// 包装
mBufferedSource = Okio.buffer(source(mResponseBody.source()));
}
return mBufferedSource;
}
// 重写调用实际的响应体的contentLength
@Override
public long contentLength() {
return mResponseBody.contentLength();
}
// 重写调用实际的响应体的contentType
@Override
public MediaType contentType() {
return mResponseBody.contentType();
}
/**
* @return 读取,回调进度接口
*/
private Source source(Source source) {
return new ForwardingSource(source) {
// 当前读取字节数
long totalBytesRead = 0L;
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
// 增加当前读取的字节数,如果读取完成了bytesRead会返回-1
totalBytesRead += bytesRead != -1 ? bytesRead : 0;
// 回调,如果contentLength()不知道长度,会返回-1
if (progressListener != null)
progressListener.onProgress(totalBytesRead, mResponseBody.contentLength(), bytesRead == -1);
return bytesRead;
}
};
}
}