com.cmonbaby.http.utils.HttpClientHelper Maven / Gradle / Ivy
Show all versions of http_lower Show documentation
package com.cmonbaby.http.utils;
import com.cmonbaby.http.stream.FileRequestBody;
import com.cmonbaby.http.stream.FileResponseBody;
import com.cmonbaby.http.stream.listener.ProgressListener;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Author: Simon
*
QO: 8950764
*
Email: [email protected]
*
WebSize: https://www.cmonbaby.com
*
Version: 1.0.0
*
Date: 2020/12/28
*
Description: 请求辅助类
*/
class HttpClientHelper {
/**
* 包装OkHttpClient,用于下载文件的回调
*
*
* @param mOkHttpClient OkHttp3对象
* @param progressListener 进度回调接口
* @return 包装后的OkHttpClient
*/
static OkHttpClient addProgressResponseListener(OkHttpClient.Builder mOkHttpClient,
ProgressListener progressListener) {
if (mOkHttpClient == null) mOkHttpClient = OkHttp3Utils.getOkHttpClient();
// 增加拦截器
mOkHttpClient.addInterceptor(chain -> {
// 拦截
Response originalResponse = chain.proceed(chain.request());
// 包装响应体并返回
return originalResponse.newBuilder()
.body(new FileResponseBody(originalResponse.body(), progressListener))
.build();
});
return mOkHttpClient.build();
}
/**
* 包装OkHttpClient,用于上传文件的回调
*
*
* @param mOkHttpClient OkHttp3对象
* @param progressListener 进度回调接口
* @return 包装后的OkHttpClient
*/
static OkHttpClient addProgressRequestListener(OkHttpClient.Builder mOkHttpClient,
ProgressListener progressListener) {
if (mOkHttpClient == null) mOkHttpClient = OkHttp3Utils.getOkHttpClient();
// 增加拦截器
mOkHttpClient.addInterceptor(chain -> {
Request original = chain.request();
Request request = original.newBuilder()
.method(original.method(), new FileRequestBody(original.body(), progressListener))
.build();
return chain.proceed(request);
});
return mOkHttpClient.build();
}
}