嘿,今天的你过的还好吗
接上一篇,我整理了一下直接上代码
构造类
public class RetrofitManager {
// 请求的URL前缀 要以"/"结尾
private static final String BASEURL = "url";
private static Retrofit retrofit;
private static RetrofitManager retrofitManager;
//提供共有的方法供外界访问
public static RetrofitManager newInstance() {
if (retrofitManager == null) {
synchronized (RetrofitManager.class) {
retrofitManager = new RetrofitManager();
}
}
return retrofitManager;
}
//通过动态代理生成相应的Http请求
public <T> T creat(Class<T> t) {
return retrofit.create(t);
}
//构造方法私有化
private RetrofitManager() {
retrofit = getRetrofit();
}
//构建Ok请求
private OkHttpClient getOkHttpClient() {
return new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY))
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
}
//构建Retrofit
private Retrofit getRetrofit() {
return new Retrofit.Builder()
//设置网络请求BaseUrl地址
.baseUrl(BASEURL )
//设置数据解析器
.client(getOkHttpClient())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
然后是API
public interface RetorFitApi {
@POST("pi.User.getPratique.hf")
Observable<BaseResult<MassageBean>> getPratiques(@Body CurrencyBean currencyBean);
}
最后是使用
CurrencyBean currencyBean = new CurrencyBean();
currencyBean.setAppType("2");
currencyBean.setLoginKey("9527");
currencyBean.setSystemID("2");
RetrofitManager.newInstance()
.creat(RetorFitApi.class)
.getPratiques(currencyBean)
.subscribeOn(Schedulers.io())
.compose(new ResponseTransformer())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<MassageBean>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
Log.e("sansuiban", "aaaaa: " + d );
}
@Override
public void onNext(@NonNull MassageBean massageBean) {
Log.e("sansuiban", "aaaaa: " + massageBean.getDengLu().get(0).getBusinessName().toString());
}
@Override
public void onError(@NonNull Throwable e) {
Log.e("sansuiban", "bbbbb: " + e );
}
@Override
public void onComplete() {
Log.e("sansuiban", "onSubscribe: " );
}
});
ok完成
网友评论