获取表头
public class getHeaders implements Interceptor {
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Request request = chain.request();
Request newRequest = request.newBuilder()
.addHeader("userId","84212")
.addHeader("sessionId","161525703688584212")
.build();
return chain.proceed(newRequest);
}
}
请求数据
public class RetrofitUtil {
private static RetrofitUtil retrofitUtil;
private Retrofit retrofit;
// 通过参数来获取数据的接口
private ApiServices apiServices;
private RetrofitUtil() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.addInterceptor(new getHeaders())
.build();
retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
public ApiServices getApiServices() {
if (apiServices == null) {
apiServices = retrofit.create(ApiServices.class);
}
return apiServices;
}
//''
public static RetrofitUtil getRetrofitUtil() {
if (retrofitUtil == null) {
synchronized (RetrofitUtil.class){
if (retrofitUtil == null) {
retrofitUtil = new RetrofitUtil();
}
}
}
return retrofitUtil;
}
}
判断网络链接是否正常
public class HttpUtil {
public static boolean isConnected(Context context){
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo!=null && networkInfo.isConnected()) {
return true;
}else{
return false;
}
}
}