一;此乃一个retrofit+Rxjava实现网络请求封装的一个工具类;
下边是参考依赖;
compile 'io.reactivex.rxjava2:rxjava:2.0.8'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
二,如下工具类;
public class HttpManager {
private static HttpManager instance;
private static Retrofit retrofit;
private HttpManager() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> {
LogUtil.i("retrofit = " + message); // 打印retrofit日志
}).setLevel(HttpLoggingInterceptor.Level.BODY);
// Interceptor headerInterceptor = chain -> {
// Request request = chain.request()
// .newBuilder()
// .addHeader("token", SharePreferenceUtils.get(HaoYunApp.getAppContext(), LoginQuery.LOGIN_TOKEN))
// .addHeader("userId", SharePreferenceUtils.getInt(HaoYunApp.getAppContext(), LoginQuery.LOGIN_USERID) + "")
// .addHeader("devId", DeviceUtils.getDeviceID(HaoYunApp.getAppContext()))
// .build();
// return chain.proceed(request);
// };
OkHttpClient mOkHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(10, TimeUnit.SECONDS) // 设置超时时间
.readTimeout(10, TimeUnit.SECONDS) // 设置读取超时时间
.writeTimeout(10, TimeUnit.SECONDS) // 设置写入超时时间
.cache(new Cache(HaoYunApp.getInstance().getCacheDir(), 10 * 1024 * 1024)) // 10MB缓存
// .addInterceptor(headerInterceptor) // 添加header信息
.addInterceptor(loggingInterceptor)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(Interface.COMMON)
.client(mOkHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
public static HttpManager getInstance() {
if (null == instance) {
synchronized (HttpManager.class) {
if (null == instance) {
instance = new HttpManager();
}
}
}
return instance;
}
public static IApi getHttpImpl() {
getInstance();
return retrofit.create(IApi.class);
}
public Retrofit getRetrofit() {
return retrofit;
}
}
Retrofit+Rxjava请求工具类
最新推荐文章于 2025-05-28 23:39:14 发布