RxJava+Retrofit+OkHttp,一步一步封装网络框架;

使用RxJava+Retrofit+OkHttp,首先在build.gradle添加:

 

compile 'com.squareup.okhttp3:okhttp:3.8.1'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
compile "io.reactivex.rxjava2:rxjava:2.1.2"
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'com.orhanobut:logger:2.2.0'
compile "com.squareup.okhttp3:logging-interceptor:3.8.1"

一、Retrofit网络库的使用;

1、创建retrofit的实例:

Retrofit retrofit= new Retrofit.Builder()
        .baseUrl("https://movie.douban.com")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

2、创建一个接口,里面放的是网络请求的Url;

 

public interface DouBanApi {
//    http://api.douban.com/v2/movie/top250?start=25&count=25
    @GET("v2/movie/top250")
    Call<JsonObject> getcTop250(@Query("start") int start, @Query("count") int count);
}

3、使用retrofit请求网络:

 

DouBanApi urlAPI = retrofit.create(DouBanApi.class);
urlAPI.getcTop250(0,20).enqueue(new Callback<JsonObject>() {
    @Override
    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {

    }

    @Override
    public void onFailure(Call<JsonObject> call, Throwable t) {

    }
});

它这个请求完成后,自动把请求的结果转换成了Json数据;请求的结果太多了我就不写了;

二、Retrofit配合RxJava使用;

1、接口中的Api返回类型我们给它改为RxJava的被观察者;

 

public interface DouBanApi {
//    http://api.douban.com/v2/movie/top250?start=25&count=25
    @GET("v2/movie/top250")
    Observable<JsonObject> getTop250(@Query("start") int start,@Query("count") int count);
}

2、Retrofit+RxJava请求网络:

 

private void RxjavaandRetrofit(){
    new Retrofit.Builder()
            .baseUrl("https://movie.douban.com")
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
            .create(DouBanApi.class)
            .getTop250(0,20)
            .subscribeOn(Schedulers.io()) //被观察者 开子线程请求网络
            .observeOn(AndroidSchedulers.mainThread()) //观察者 切换到主线程
            .subscribe(new Observer<JsonObject>() {
                @Override
                public void onSubscribe(Disposable d) {
                    
                }

                @Override
                public void onNext(JsonObject jsonObject) {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
}

这样就完成了RxJava+Retrofit请求网络;

三:添加OkHttp配置;

okhttp可以设置很多的东西,请求头、拦截器、Log打印、请求超时时间......(最主要的okhttp的速度比Retrofit快很多);

 

OkHttpClient.Builder builder = new OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30,TimeUnit.SECONDS)
        .writeTimeout(30,TimeUnit.SECONDS)
        .addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder request = chain.request().newBuilder();
        request.addHeader("Accept","*/*");
        //添加拦截器
        return chain.proceed(request.build());
    }
});

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
    @Override
    public void log(String message) {
        Logger.i(message);
    }
}).setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(loggingInterceptor);
Retrofit.Builder retrofit= new Retrofit.Builder()
        .baseUrl("https://movie.douban.com")
        .addConverterFactory(GsonConverterFactory.create());
retrofit.client(builder.build()).build();

这样Retrofit的网络请求就会使用OkHttp的内核了;

四、RxJava+Retrofit+OkHttp封装;

作为一个聪明的程序猿,不!作为一个聪明的攻城狮,我们每次请求不可能都写这么多的代码;来封装一下:

 

public class RetrofitUtils {
/*
http://api.douban.com/
 */
    private String baseUrl = "http://api.douban.com/";

    private static final RetrofitUtils retrofitUtils = new RetrofitUtils();

    public static RetrofitUtils get(){
        return retrofitUtils;
    }
    private static volatile Retrofit retrofit;
     public RetrofitUtils(){
         Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                 .baseUrl(baseUrl)
                 .addConverterFactory(GsonConverterFactory.create())
                 .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()));
         OkHttpClient.Builder builder = new OkHttpClient.Builder()
                 .connectTimeout(30, TimeUnit.SECONDS)
                 .readTimeout(30,TimeUnit.SECONDS)
                 .writeTimeout(30,TimeUnit.SECONDS)
                 .addInterceptor(new Interceptor() {
             @Override
             public Response intercept(Chain chain) throws IOException {
                 Request.Builder request = chain.request().newBuilder();
                 request.addHeader("Accept","*/*");
                 //添加拦截器
                 return chain.proceed(request.build());
             }
         });

         HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
             @Override
             public void log(String message) {
                 Logger.i(message);
             }
         }).setLevel(HttpLoggingInterceptor.Level.BODY);
         builder.addInterceptor(loggingInterceptor);
         retrofit = retrofitBuilder.client(builder.build()).build();
     }
    public static  <T> T create(Class<T> cls) {
        return retrofit.create(cls);
    }
}

如何使用呢?

 

private void doubanTest() {
   RetrofitUtils.get().create(DouBanApi.class)
           .getTop250(0,5)
           .subscribe(new Consumer<JsonObject>() {
               @Override
               public void accept(JsonObject jsonObject) throws Exception {
                 //正常请求成功
               }
           }, new Consumer<Throwable>() {
               @Override
               public void accept(Throwable throwable) throws Exception {
              //请求异常时
               }
           });
}

简单不简单,还有谁!!!

 

其实,我们可以发现,RxJava+Retrofit+OkHttp它们3个的配合使用:

RxJava主要是用来实现线程的切换的。我们可以在指定订阅的在哪个线程,观察在哪个线程。我们可以通过操作符进行数据变换。整个过程都是链式的,简化逻辑;

Retrofit就是网络请求的一个架子,用它设置一些参数和请求的URL之类的;

OkHttp是网络请求的内核,实际的网络请求是它发出来的

 

转载于:https://www.cnblogs.com/cuichen16/p/10785991.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值