简介
1. 定义Model
public interface Model {
@GET
Observable<AResponse> getA(@Body ARequest request);
@GET
Observable<BResponse> getB(@Body BRequest request);
}
2. 创建OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.readTimeout(10, TimeUnit.SECONDS)
.connectTimeout(9, TimeUnit.SECONDS)
.build();
3. 构建Gson
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd hh:mm:ss")
.create();
4. 创建Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.baidu.com/")
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
5. 创建Model
Model model = retrofit.create(Model.class);
6. 执行网络请求
model.getA(new ARequest())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<AResponse>() {
@Override
public void onSubscribe(Disposable d) { }
@Override
public void onNext(AResponse value) { }
@Override
public void onError(Throwable e) { }
@Override
public void onComplete() { }
});
网友评论