当前位置: 代码迷 >> 综合 >> RxJava+Retrofit
  详细解决方案

RxJava+Retrofit

热度:58   发布时间:2023-10-10 12:58:07.0

最近在研究Retrofit 和 rxjava。写的简单的demo;
首先我们来实现retrofit:
1 添加依赖

 compile 'com.squareup.retrofit2:retrofit:2.1.0'//这个使用的事Gson解析 想用JackFast或其他请看参考文档添加compile 'com.squareup.retrofit2:converter-gson:2.0.1'

API接口

//需要请求的API https://api.github.com/repos/square/retrofit/contributors
// 其中的owner=square repo = retrofit
public interface APIinterface {
    @GET("repos/{owner}/{repo}/contributors")Call<List<ResponsBeen>> retrofitTest(@Path("owner" )String owner, @Path("repo") String repo);
}

初始化retrofit

 Retrofit retrofit = new Retrofit.Builder().baseUrl(BaseUrl.BASE_URL)//使用Gson解析                .addConverterFactory(GsonConverterFactory.create()).build();

构建API

     APIinterface apIinterface = retrofit.create(APIinterface.class);Call<List<ResponsBeen>> call = apIinterface.retrofitTest(userName, repo);

将请求插入队列中

call.enqueue(new Callback<List<ResponsBeen>>() {@Overridepublic void onResponse(Call<List<ResponsBeen>> call, Response<List<ResponsBeen>> response) {Log.d("MainActivity", "访问成功");//结果已经过Gson解析过了List<ResponsBeen> responsBeens = response.body();for (ResponsBeen responsBeen : responsBeens){Log.d("MainActivity", responsBeen.getLogin());}}@Overridepublic void onFailure(Call<List<ResponsBeen>> call, Throwable t) {Log.d("MainActivity", "访问失败");}});}

以上就是一个完整的retrofit网络请求


那么我们怎么打印网络请求的log呢

因为retrofit是封装的OKHttp,所以我们可以用OKHttp的LOG来用
这里要添加OKHttp3的依赖

    compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'
//初始化logHttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);OkHttpClient okHttpClient =new OkHttpClient.Builder().addInterceptor(interceptor).build();Retrofit retrofit = new Retrofit.Builder().client(okHttpClient).baseUrl(BaseUrl.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();

以上是打印log

如何配合rxandroid
添加依赖

compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'
compile 'io.reactivex:rxandroid:1.1.0'

修改APIInterface 将返回对象改为Observable

 @GET("repos/{owner}/{repo}/contributors")Observable<List<ResponsBeen>> rxandroidTest(@Path("owner" )String owner, @Path("repo") String repo);

给retrofit添加callAdapterFactory

Retrofit retrofit = new Retrofit.Builder().client(okHttpClient).baseUrl(BaseUrl.BASE_URL).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build();APIinterface apIinterface = retrofit.create(APIinterface.class);

初始化rxandroid相关

CompositeSubscription compositeSubscription = new CompositeSubscription();compositeSubscription.add(apIinterface.rxandroidTest(userName,repo).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<List<ResponsBeen>>() {@Overridepublic void onCompleted() {}@Overridepublic void onError(Throwable e) {}@Overridepublic void onNext(List<ResponsBeen> responsBeens) {for (ResponsBeen been : responsBeens){Log.d("MainActivity", been.getLogin());}}}));

综上我们可以看到制作API的部分我们可以封装一下

public class API {private API() {}public static <T>T getAPI(final Class<T> apiInterface){
// 初始化LogHttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// 初始化并设置HttpClientOkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(interceptor).build();
// 初始化并设置retrofitRetrofit retrofit = new Retrofit.Builder().client(okHttpClient).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create()).baseUrl(BaseUrl.BASE_URL).build();
// 返回APIreturn retrofit.create(apiInterface);} 
}

好了这样就基本写完了