RxJava+Retrofit實現網絡請求
阿新 • • 發佈:2017-09-22
urlencode lencod ava nds sre square ret timeunit ann
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 interfaceRetrofitAPI { //登錄 @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") intchannel); }
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實現網絡請求