package com.anshuangxin.quarter.utils;
import android.os.Environment;
import java.io.File;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* author:Created by WangZhiQiang on 2018/3/9.
*/
public class RetrofitUtil {
private static RetrofitUtil retrofitUtils;//工具类对象
private static ApiService apiFunction;//请求网络接口
public static OkHttpClient okHttpClient;
//静态快,获取OkHttpClient对象
static {
getOkHttpClient();
}
//单例锁模式
public static RetrofitUtil getInstence() {
if (retrofitUtils == null) {
synchronized (RetrofitUtil.class) {
if (retrofitUtils == null) {
retrofitUtils = new RetrofitUtil();
}
}
}
return retrofitUtils;
}
//单例模式获取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()
//打印拦截器日志
//.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("https://www.zhaoapi.cn/")
.addConverterFactory(GsonConverterFactory.create())//添加gson转换器
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加rxjava转换器
.client(okHttpClient)//添加okhttp
.build();
apiFunction = retrofit.create(ApiService.class);
}
//拦截器(POST的拦截器)
static class MyInter implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
//获取原来的body
Request request = chain.request();
RequestBody body = request.body();
if (body instanceof FormBody) {
Log.e("tsg", "okhttp");
//遍历原来的所有参数,加到新的Body里面,最后将公共参数加到新的Body
FormBody.Builder newBuilder = new FormBody.Builder();
for (int i = 0; i < ((FormBody) body).size(); i++) {
String name = ((FormBody) body).name(i);
String value = ((FormBody) body).value(i);
//放入新的
newBuilder.add(name, value);
}
//在将公共参数添加进去
FormBody newBody = newBuilder.add("source", "android").
add("appVersion", "101")
.build();
//创建新的请求
Request build = request.newBuilder().post(newBody).build();
Response response = chain.proceed(build);
Log.e("MyInter", response.body().toString());
return response;
}
return null;
}
}
//获取
public ApiService API() {
return apiFunction;
}
}