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();
}
}); }