Rxjava+Retrofit+Okhttp封装(主要是怎么用)记录

一:需要使用到的三方库

 version = [
            retrofitSdkVersion      : "2.4.0",
            okhttpVersion              : "3.11.0"
    ]

    dependencies = [
            //rx
            "rxjava"        : "io.reactivex.rxjava2:rxjava:2.1.5",
            "rxandroid"     : "io.reactivex.rxjava2:rxandroid:2.0.1",

            //network
            "retrofit"                      : "com.squareup.retrofit2:retrofit:${version["retrofitSdkVersion"]}",
            "retrofit-converter-gson"       : "com.squareup.retrofit2:converter-gson:${version["retrofitSdkVersion"]}",
            "retrofit-converter-scalars"    : "com.squareup.retrofit2:converter-scalars:${version["retrofitSdkVersion"]}",
            "retrofit-adapter-rxjava"      : "com.squareup.retrofit2:adapter-rxjava:${version["retrofitSdkVersion"]}",
            "retrofit-adapter-rxjava2"     : "com.squareup.retrofit2:adapter-rxjava2:${version["retrofitSdkVersion"]}",
            "okhttp3"                       : "com.squareup.okhttp3:okhttp:${version["okhttpVersion"]}",
            "logging-interceptor"          : "com.squareup.okhttp3:logging-interceptor:${version["okhttpVersion"]}",

    ]

二:核心管理类 RetrofitServiceManager 有哪些功能

 1,初始化Okttp3:连接,读 写超时时间;https,请求头,log日志,添加参数 ,缓存等拦截配置;

 2,Retrofit,设置BaseUrl,添加对那些回调库的支持;


import android.os.Environment;

import java.io.File;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class RetrofitServiceManager {
    private static final int DEFAULT_TIME_OUT = 10;//超时时间
    private static final int DEFAULT_READ_TIME_OUT = 10;//读取时间
    private static final int DEFAULT_WRITE_TIME_OUT = 10;//读取时间

    private Retrofit mRetrofit;

    public RetrofitServiceManager() {
        //OkHttpClient配置
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);
        builder.readTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS);
        builder.writeTimeout(DEFAULT_WRITE_TIME_OUT, TimeUnit.SECONDS);
        //TODO:设置支持所有的https请求
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        }).sslSocketFactory(sslParams.sSLSocketFactory,sslParams.trustManager);

        //TODO:cookie持久化管理

        //添加日志拦截器
        addInterceptor(builder);

        this.mRetrofit = new Retrofit.Builder()
                //设置服务器路径
                .baseUrl(ApiService.BASR_URL)
                //增加返回值为String的支持
                .addConverterFactory((ScalarsConverterFactory.create()))
                //添加转化库,默认是Gson
                .addConverterFactory(GsonConverterFactory.create())
                //添加回调库,采用RxJava2
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build();
    }

    /* 添加各种拦截器
     * @param builder
     */
    private void addInterceptor(OkHttpClient.Builder builder) {
         //添加日志拦截器 会把请求信息链接,返回结果打印出来;
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        HttpHeaderInterceptor httpHeaderInterceptor = new HttpHeaderInterceptor.Builder().build();

        //日志拦截
        builder.addInterceptor(loggingInterceptor);
        //头部参数拦截
        builder.addInterceptor(httpHeaderInterceptor);
        //缓存拦截
        builder.addInterceptor(new HttpCacheInterceptor());
        //请求参数拦截
        builder.addInterceptor(new CommonParamsInterceptor());

      //  builder.cache(new Cache(new File(Environment.getExternalStorageDirectory() + "/RxJavaDemo"), 1024 * 1024 * 10));
    }

    public static final RetrofitServiceManager getInstance(){
        return SingletonHolder.retrofitServiceManager;
    }

    public  T create(Class tClass){
        return mRetrofit.create(tClass);
    }

    //单例 饿汉模式
    private static class SingletonHolder{
        private static final RetrofitServiceManager retrofitServiceManager = new RetrofitServiceManager();
    }
}

三:ApiService 书写示列;

public interface ApiService {

    String BASR_URL = "http://test.bigbuy.win/";

    //缓存一个小时
    @Headers("Cache-Control: public, max-age=3600")
    @GET("appapi/index/banner/id/1?cmd=home_slider_top&limit=5")
    Observable>> getBanner();

}

四:调用方法: 注释部分是之前写法;

//        RetrofitServiceManager.getInstance().create(ApiService.class)
//                .getBanner().subscribeOn(Schedulers.io())
//                .subscribeOn(Schedulers.newThread())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//
//                    }
//
//                    @Override
//                    public void onNext(String s) {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });


        //    第二种写法看起来代码更简洁
                RetrofitServiceManager.getInstance().create(ApiService.class)
                        .getBanner()
                        .compose(RxUtils.>>rxSchedulerHelper()) //切换线程
                        .compose(RxUtils.>handleResult()) //处理结果回调的地方
                        .subscribe(new BaseObserver>(this) {
                            @Override
                            protected void onSuccess(List bannerEntities) {
                                Log.d("print", "--->addSubscribe" + bannerEntities.size());
                            }
                        });

五:BaseResponse 基础类写法

public class BaseResponse {
    private int code;
    private String msg;
    private T model;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getModel() {
        return model;
    }

    public void setModel(T model) {
        this.model = model;
    }

    public boolean isSuccess(){
        return code == 0;
    }

六“ 顺便贴一下CommonParamsInterceptor

/**
 * 网络请求公共参数插入器
 */
public class CommonParamsInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Log.d("CommonParamsInterceptor","intercept insert params");
        Request request = chain.request();
        if (request.method().equals("GET")){
            HttpUrl httpUrl = request.url().newBuilder()
//                    .addQueryParameter("version", "xxx")
//                    .addQueryParameter("device", "Android")
//                    .addQueryParameter("timestamp", String.valueOf(System.currentTimeMillis()))
            .build();
            request = request.newBuilder().url(httpUrl).build();
        } else if (request.method().equals("POST")){
            if (request.body() instanceof FormBody){
                FormBody.Builder bodyBuilder = new FormBody.Builder();
                FormBody formBody = (FormBody) request.body();

                for (int i = 0; i < formBody.size(); i++) {
                    bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
                }

                formBody = bodyBuilder
//                        .addEncoded("version", "xxx")
//                        .addEncoded("device", "Android")
//                        .addEncoded("timestamp", String.valueOf(System.currentTimeMillis()))
                        .build();

                request = request.newBuilder().post(formBody).build();
            }
        }

        return chain.proceed(request);
    }

demo地址:https://download.csdn.net/download/androidforme/10989201

你可能感兴趣的:(Android进阶笔记)