public static final int DEFAULT_TIMEOUT = 5;
public static final String URL="https://www.zhaoapi.cn/";
private Retrofit mRetrofit;
private ApiService mApiService;
private static RetrofitUtil mInstance;
/**
* 私有构造方法
*/
private RetrofitUtil(){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
builder.addInterceptor(interceptor).addInterceptor(new MyInterceptor());//网络拦
mRetrofit = new Retrofit.Builder()
.client(builder.build())
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
mApiService = mRetrofit.create(ApiService.class);
}
public static RetrofitUtil getInstance(){
if (mInstance == null){
synchronized (RetrofitUtil.class){
if (null == mInstance) {
mInstance = new RetrofitUtil();
}
}
}
return mInstance;
}
public ApiService getUsers(){
return mApiService;
}
private class MyInterceptor implements Interceptor {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl httpUrl = request
.url()
.newBuilder()
.addQueryParameter("source", "android")
.build();
Request requestNew = request
.newBuilder()
.url(httpUrl)
.build();
return chain.proceed(requestNew);
}
}
model层引用:
黄油刀和rxjava2+retrofit2依赖
implementation 'com.jakewharton:butterknife:8.8.1’
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'io.reactivex.rxjava2:rxjava:2.1.12'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
implementation 'com.afollestad.material-dialogs:core:0.9.6.0'
implementation 'com.afollestad.material-dialogs:commons:0.9.6.0'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.google.code.gson:gson:2.8.2'
RetrofitUtil.getInstance().getUsers()
.getProductCatagory(cid)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DisposableSubscriber<ProductCatagoryBean>() {
@Override
public void onNext(ProductCatagoryBean productCatagoryBeanBaseBean) {
Log.e(TAG, "onNext: "+productCatagoryBeanBaseBean.getMsg() );
toHome.toBack(productCatagoryBeanBaseBean);
}
@Override
public void onError(Throwable t) {
Log.e(TAG, "onError: "+t.getMessage() );
}
@Override
public void onComplete() {
}
});
}
retrofit接口引用:
@GET("product/getProductCatagory")
Flowable<ProductCatagoryBean> getProductCatagory(@Query("cid") String cid);