Retrofit 和 Rxjava 网络封装
首先第一步就是导依赖
api 'io.reactivex.rxjava2:rxjava:2.2.8'
api 'io.reactivex.rxjava2:rxandroid:2.1.1'
api 'com.squareup.okhttp3:okhttp:3.12.1'
//日志拦截器
api 'com.squareup.okhttp3:logging-interceptor:3.11.0'
//网络请求封装框架
api 'com.squareup.retrofit2:retrofit:2.6.2'
//网络请求对象解析器
api 'com.squareup.retrofit2:converter-gson:2.6.2'
//线程异常任务调度
api 'com.squareup.retrofit2:adapter-rxjava2:2.6.2'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'// log拦截器依赖
第二步在新的类里写一个单例
private static volatile MyHttp instance;
public static synchronized MyHttp getInstance(){
if (instance==null){
instance=new MyHttp();
}
return instance;
}
第三步 网络请求
public Retrofit retrofit(){
// 打印日志,添加请求头
HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder()
//请求时间
.readTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.connectTimeout(5,TimeUnit.SECONDS)
//打印日志
.addInterceptor(httpLoggingInterceptor)
//添加请求头 创建insertInterceptor方法
.addInterceptor(insertInterceptor());
Retrofit.Builder builder1 = new Retrofit.Builder();
builder1
.baseUrl("需要的请求的网址")
.client(builder.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return builder1.build();
}
private Interceptor insertInterceptor() {
Interceptor interceptor=new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request.newBuilder().addHeader("请求头key","请求头value").build();
Response proceed = chain.proceed(request);
return proceed;
}
};
return interceptor;
}