import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* @ClassName RetrofitUtil
* @Description 网络请求封装
*/
public class RetrofitUtil {
private static RetrofitUtil instance;
private final Retrofit retrofit;
//单例模式
public static RetrofitUtil getInstance(){
if (instance == null){
synchronized (RetrofitUtil.class){
if (instance == null){
instance = new RetrofitUtil();
}
}
}
return instance;
}
//网络请求
private RetrofitUtil(){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient
.Builder()
.addInterceptor(interceptor)
//.addInterceptor(new MoreBaseUrlInterceptor())
.addInterceptor(new HandlerUtils())
.addInterceptor(new TokenInterceptor())
.connectTimeout(20000,TimeUnit.SECONDS)
.readTimeout(20000,TimeUnit.MILLISECONDS)
.writeTimeout(20000,TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.sslSocketFactory(TrustAllCerts.createSSLSocketFactory())
.hostnameVerifier(new TrustAllCerts.TrustAllHostnameVerifier())
.build();
retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(API.BASE)
.client(okHttpClient)
.build();
}
public <T> T create(final Class<T> service){
return retrofit.create(service);
}
}
HandlerUtils
import android.util.Log;
import androidx.annotation.NonNull;
import com.jzxny.jiuzihaoche.base.MyApplication;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class HandlerUtils implements Interceptor {
@NonNull
@Override
public Response intercept(Chain chain) throws IOException {
String token = SpUtils.getString(MyApplication.context, "access_token");
//SpUtils是SharedPreferences的工具类,自行实现
if (token.isEmpty()) {
Request originalRequest = chain.request();
return chain.proceed(originalRequest);
}else{
Request originalRequest = chain.request();
Request updateRequest = originalRequest.newBuilder().header("Authorization", "Bearer "+token).build();
return chain.proceed(updateRequest);
}
}
}
|