RxJava+Retrofit

最近在研究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>>() {
            @Override
            public 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());
                }
            }

            @Override
            public 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'
//初始化log

        HttpLoggingInterceptor 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>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public 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){
//        初始化Log
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//        初始化并设置HttpClient
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build();
//        初始化并设置retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(BaseUrl.BASE_URL)
                .build();
//        返回API
        return retrofit.create(apiInterface);

    } 
}

好了这样就基本写完了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值