Retrofit和RxJava的網路請求封裝
阿新 • • 發佈:2019-02-18
public class RetrofitUtil {
private static RetrofitUtil retrofitUtil;//工具類物件
private static RetrofitService retrofitService;//請求網路介面
public static OkHttpClient okHttpClient;
//靜態快,獲取OkHttpClient物件
static {
getOkHttpClient();
}
//單例鎖模式
public static RetrofitUtil getInstence() {
if (retrofitUtil == null) {
synchronized (RetrofitUtil.class) {
if (retrofitUtil == null) {
retrofitUtil = new RetrofitUtil();
}
}
}
return retrofitUtil;
}
//單例模式獲取okhttp
public static OkHttpClient getOkHttpClient() {
if (okHttpClient == null) {
synchronized (OkHttpClient.class) {
if (okHttpClient == null) {
File fileDir = new File(Environment.getExternalStorageDirectory(), "cache");
long fileSize = 10 * 1024 * 1024;
okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new RetrofitIntercepter())
//列印攔截器日誌
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.connectTimeout(15, TimeUnit.SECONDS)//設定連線超時時間
.readTimeout(15, TimeUnit.SECONDS)//設定讀取超時時間
.writeTimeout(15, TimeUnit.SECONDS)//設定寫入超時時間
//.cache(new Cache(fileDir,fileSize))//寫入sd卡
.build();
}
}
}
return okHttpClient;
}
//私有的無參構造
private RetrofitUtil() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(HttpConfig.baseUrl)
.addConverterFactory(GsonConverterFactory.create())//新增gson轉換器
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//新增rxjava轉換器
.client(okHttpClient)//新增okhttp
.build();
retrofitService = retrofit.create(RetrofitService.class);
}
//公共引數攔截器
static class RetrofitIntercepter implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RequestBody body = request.body();
if (body instanceof FormBody) {
FormBody.Builder builder = new FormBody.Builder();
for (int i = 0; i < ((FormBody) body).size(); i++) {
String key = ((FormBody) body).name(i);
String value = ((FormBody) body).value(i);
builder.add(key, value);
}
builder.add("source", "android");//appVersion=101
builder.add("appVersion", "101");
FormBody formBody = builder.build();
Request request1 = request.newBuilder().post(formBody).build();
Response response = chain.proceed(request1);
return response;
}
return null;
}
}
//獲取
public RetrofitService API() {
return retrofitService;
}
}