应用场景:1.服务端为了统计各个平台、版本的使用情况,有时在接口中要求传递统一的诸如version(客户端版本)、os(客户端平台android/iOS)、userId等参数,这时如果在接口中一一添加就比较繁琐了,考虑做全局处理;另外,一次登录成功后,登录状态都是有时效的,所以在发生登录失效后,需要自动重新刷新登录状态,而且一般情况下,单个请求在发出前是没法判断是否已经登录超时的,所以就需要一个全局的处理方案。
其实这个与Retrofit2/Rxjava貌似没有关系,之所以标题里提到这个,是因为我的项目是结合这俩库用的,我在搜索这类问题的解决方法时就是从Retrofit2/Rxjava的retryWhen方法下手的,后来发现直接在OkHttpClient添加拦截器,即可实现想要的效果,而且是全局性的,这应该是这类问题的最简单解决方式了。
主要代码如下:
Network.java
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.BufferedSource;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class Network {
private static final String TAG = "Network";
private static APIService apis;
private static ReLoginService reLoginService;
private static Converter.Factory mExtraGsonConverterFactory = ExtraGsonConverterFactory.create();
private static CallAdapter.Factory rxJavaCallAdapterFactory = RxJavaCallAdapterFactory.create();
public static APIService getAPIService() {
if (apis == null) {
// TODO 最后关闭日志
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);