RxJava+Retrofit实现网络请求
Posted _yegong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RxJava+Retrofit实现网络请求相关的知识,希望对你有一定的参考价值。
RxJava+Retrofit实现网络请求:
首先要添加依赖
compile ‘io.reactivex:rxjava:x.y.z‘ compile ‘io.reactivex:rxandroid:1.0.1‘ compile ‘com.squareup.retrofit2:retrofit:2.0.2‘ compile ‘com.squareup.retrofit2:converter-gson:2.0.2‘ compile ‘com.squareup.retrofit2:adapter-rxjava:2.0.2‘
1、创建Retrofit请求的网络接口
public interface RetrofitAPI { //登录 @FormUrlEncoded @POST(Constant.LOGIN) Observable<Responseinfo<LoginBean>> setLogin(@Field("mobile") String phone, @Field("pwd") String pwd); //注册 @FormUrlEncoded @POST(Constant.REGISTE) Observable<Responseinfo<RegisteBean>> getUserId(@Field("mobile") String id, @Field("pwd") String token, @Field("channel") int channel); }
2、创建Retrofit和RxJava的对象
public class RetrofitHelper { //设置网络请求默认的超时时间 private static final int DEFAULT_TIME_OUT = 10; private static Retrofit sRetrofit; private static OkHttpClient sOKHttpClient; public static RetrofitAPI getRetrofitAPI(){ return getInstance().create(RetrofitAPI.class); } public static Retrofit getInstance(){ if(sRetrofit== null){ synchronized (RetrofitHelper.class){ if(sRetrofit == null){ sRetrofit = new Retrofit.Builder() .baseUrl(Constant.BASEURL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(getsOKHttpClient()) .build(); } } } return sRetrofit; } public static OkHttpClient getsOKHttpClient(){ if(sOKHttpClient == null){ synchronized (RetrofitHelper.class){ if(sOKHttpClient == null){ sOKHttpClient = new OkHttpClient.Builder() .connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS) .readTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS) .writeTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS) .build(); } } } return sOKHttpClient; } }
3、开启网络请求
private void requestLoginNet(String mobile, String pwd) { //登录的接口 RetrofitHelper.getRetrofitAPI() .setLogin(mobile, pwd) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Responseinfo<LoginBean>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Responseinfo<LoginBean> response) { if (response == null){ return; } int result = response.getResult(); } }); }
以上是关于RxJava+Retrofit实现网络请求的主要内容,如果未能解决你的问题,请参考以下文章
Android OkHttp+Retrofit+Rxjava+Hilt实现网络请求框架
Android OkHttp+Retrofit+Rxjava+Hilt实现网络请求框架