您的位置:首页 > 理论基础 > 计算机网络

Android Retrofit2.0配合RxJava2.0请求网络

2018-01-07 20:27 399 查看
需要添加依赖

从上向下依次为Rxjava依赖,Rxjava依赖,Retrofit依赖,Retrofit支持自动Gson解析依赖,Retrofit支持Rxjava配合使用依赖

compile 'io.reactivex.rxjava2:rxjava:+'
compile 'io.reactivex.rxjava2:rxandroid:+'
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava2:+'

封装拦截器

public class MyIntercept implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl build = request.url()
.newBuilder()
.addQueryParameter("source", "android")//公共参数
.build();
Request requestNew = request.newBuilder()
.url(build)
.build();
return chain.proceed(requestNew);
}
}
工具类
public class RetrofitUtil {
public static Retrofit instance;
private Retrofit retrofit;

/*   *
* 封装好的拼接常用域名的方法
*
* @param baseurl*/

public static Retrofit getInstance(String baseurl){
if(instance==null){
synchronized (RetrofitUtil.class){
if(instance==null){

/*    自定义OkHttp请求
封装拦截器*/

OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new MyIntercept())
.build();
instance = new Retrofit.Builder()
.baseUrl(baseurl)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
}
}
return instance;
}
}
接口,拼接功能域名
public interface RetrofitServices {

/**
* get请求方式
* 登录的功能域名
*/
@GET("user/login")
Observable<LoginBean> getLoginMsg(@Query("mobile") String mobile, @Query("password") String password);

}在M层进行网络请求
public class LoginModel {

public void receive(String mobile, String password, final ILoginPresenter iLoginPresenter) {
RetrofitServices retrofitServices = RetrofitUtil.getInstance("http://120.27.23.105/").create(RetrofitServices.class);

retrofitServices.getLoginMsg(mobile, password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<LoginBean>() {
@Override
public void accept(LoginBean loginBean) throws Exception {
if(loginBean!=null){
iLoginPresenter.onLoginSuccess(loginBean);
}
}
});
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: