com.cmonbaby.http.utils.RetrofitUtils Maven / Gradle / Ivy
Show all versions of http_lower Show documentation
package com.cmonbaby.http.utils;
import com.cmonbaby.http.HttpManager;
import com.cmonbaby.http.converter.FastJsonConverterFactory;
import com.cmonbaby.http.rxjava.RxJavaCallAdapterFactory;
import com.cmonbaby.http.stream.listener.ProgressListener;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
/**
* Author: Simon
*
QO: 8950764
*
Email: [email protected]
*
WebSize: https://www.cmonbaby.com
*
Version: 1.0.0
*
Date: 2020/12/28
*
Description: 封装一个retrofit集成0kHttp3的抽象基类
*/
public class RetrofitUtils {
private final Retrofit mRetrofit;
private final Retrofit.Builder mRetrofitBuilder;
private static OkHttpClient.Builder mOkHttpClient;
private static RetrofitUtils retrofitUtils;
public static RetrofitUtils getInstance() {
if (retrofitUtils == null) {
synchronized (RetrofitUtils.class) {
if (retrofitUtils == null) {
retrofitUtils = new RetrofitUtils();
}
}
}
return retrofitUtils;
}
private RetrofitUtils() {
if (mOkHttpClient == null) mOkHttpClient = OkHttp3Utils.getOkHttpClient();
// Retrofit2后使用build设计模式
mRetrofitBuilder = new Retrofit.Builder()
// 设置服务器路径
.baseUrl(HttpManager.BaseUrl())
// 添加转化库,默认是FastJson
.addConverterFactory(FastJsonConverterFactory.create())
// 添加回调库,采用RxJava
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// 设置使用okhttp网络请求
.client(mOkHttpClient.build());
mRetrofit = mRetrofitBuilder.build();
}
public T createService(final Class service) {
return mRetrofit.create(service);
}
/**
* 创建带响应进度(下载进度)回调的service
*/
public T createResponseService(Class tClass, ProgressListener listener) {
return mRetrofitBuilder
.client(HttpClientHelper.addProgressResponseListener(mOkHttpClient, listener))
.build()
.create(tClass);
}
/**
* 创建带请求体进度(上传进度)回调的service
*/
public T createRequestService(Class tClass, ProgressListener listener) {
return mRetrofitBuilder
.client(HttpClientHelper.addProgressRequestListener(mOkHttpClient, listener))
.build()
.create(tClass);
}
}