美文网首页
Retrofit 探索二:RxJava+Retrofit实现网络

Retrofit 探索二:RxJava+Retrofit实现网络

作者: 烂吹笙 | 来源:发表于2017-11-17 15:34 被阅读0次

    一、环境配置

    1.1 添加网络权限
     <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    
    1.2 Retrofit、RxJava工具包加入
     //Rxjava
        compile 'io.reactivex.rxjava2:rxjava:2.1.6'
        compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
        //Retrofit
        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 'com.squareup.okhttp3:logging-interceptor:3.8.0'
    
    1.3 配置Retrofit支持Gson和RxJava
     mRetrofit = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))//支持Gson转换
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//支持RxJava
                    .baseUrl(ApiConstants.API_SERVER)
                    .client(mClient)
                    .build();
    
    1.4 配置Header
    Interceptor mHeaderInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request.Builder builder = originalRequest.newBuilder();
                //设置具体的Head内容
                builder.header("timestamp", System.currentTimeMillis() + "");
                Request.Builder requestBuilder =
                        builder.method(originalRequest.method(), originalRequest.body());
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        };
    
    1.5 缓存配置
      private Interceptor mCacheInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
    
                Request request = chain.request();
                if (!NetworkUtils.isNetworkAvailable(Initialization.getContext())) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE).build();
                }else{
                    request = request.newBuilder()
                            //网络可用 强制从网络获取数据
                            .cacheControl(CacheControl.FORCE_NETWORK)
                            .build();
                }
    
                Response response = chain.proceed(request);
                if (NetworkUtils.isNetworkAvailable(MyApplication.getContext())) {
                    int maxAge = 60; //缓存一分钟
                    String cacheControl = "public,max-age=" + maxAge;
                    return response.newBuilder()
                            .header("Cache-Control",cacheControl)
                            .removeHeader("Pragma").build();
                } else {
                    int maxStale = 60 * 60 * 24 * 7 * 4;  //4周
                    return response.newBuilder()
                            .header("Cache-Control", "public,only-if-cached,max-stale=" + maxStale)
                            .removeHeader("Pragma").build();
                }
            }
        };
    
    1.6 配置OkHttpClient
     //设置缓存路径
            File httpCacheDirectory = new File(MyApplication.getContext().getCacheDir(), "RetrofitCache");
            int cacheSize = 1024 * 1024 * 50; // 50 MiB
            Cache cache = new Cache(httpCacheDirectory, cacheSize);
    
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            mClient = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)//添加日志
                    .addInterceptor(mHeaderInterceptor)//添加Header
                    .addInterceptor(mCacheInterceptor)//添加缓存
                    .addNetworkInterceptor(mCacheInterceptor)
                    .cache(cache)
                    .connectTimeout(20, TimeUnit.SECONDS)//设置连接超时20秒
                    .build();
    

    ApiRetrofit完整代码

    package com.wj.rxcode.api;
    
    import com.google.gson.GsonBuilder;
    import com.wj.rxcode.MyApplication;
    import com.wj.rxcode.utils.NetworkUtils;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.concurrent.TimeUnit;
    
    import okhttp3.Cache;
    import okhttp3.CacheControl;
    import okhttp3.Interceptor;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.Response;
    import okhttp3.logging.HttpLoggingInterceptor;
    import retrofit2.Retrofit;
    import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
    import retrofit2.converter.gson.GsonConverterFactory;
    
    public class ApiRetrofit {
    
        private static ApiRetrofit mApiRetrofit;
    
        private final Retrofit mRetrofit;
    
        private OkHttpClient mClient;
    
        private ApiService mApiService;
    
        public static ApiRetrofit getInstance() {
            if (mApiRetrofit == null) {
                synchronized (Object.class) {
                    if (mApiRetrofit == null) {
                        mApiRetrofit = new ApiRetrofit();
                    }
                }
            }
            return mApiRetrofit;
        }
    
        public ApiService getApiService() {
            return mApiService;
        }
    
        public ApiRetrofit() {
            //设置缓存路径
            File httpCacheDirectory = new File(MyApplication.getContext().getCacheDir(), "RetrofitCache");
            int cacheSize = 1024 * 1024 * 50; // 50 MiB
            Cache cache = new Cache(httpCacheDirectory, cacheSize);
    
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            mClient = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)//添加日志
                    .addInterceptor(mHeaderInterceptor)//添加Header
                    .addInterceptor(mCacheInterceptor)//添加缓存
                    .addNetworkInterceptor(mCacheInterceptor)
                    .cache(cache)
                    .connectTimeout(20, TimeUnit.SECONDS)//设置连接超时20秒
                    .build();
    
            mRetrofit = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))//支持Gson转换
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//支持RxJava
                    .baseUrl(ApiConstants.API_SERVER)
                    .client(mClient)
                    .build();
    
            mApiService = mRetrofit.create(ApiService.class);
        }
    
        //缓存配置
        private Interceptor mCacheInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
    
                Request request = chain.request();
               if (!NetworkUtils.isNetworkAvailable(Initialization.getContext())) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE).build();
                }else{
                    request = request.newBuilder()
                            //网络可用 强制从网络获取数据
                            .cacheControl(CacheControl.FORCE_NETWORK)
                            .build();
                }
    
                Response response = chain.proceed(request);
                if (NetworkUtils.isNetworkAvailable(MyApplication.getContext())) {
                    int maxAge = 60; //缓存一分钟
                    String cacheControl = "public,max-age=" + maxAge;
                    return response.newBuilder()
                            .header("Cache-Control",cacheControl)
                            .removeHeader("Pragma").build();
                } else {
                    int maxStale = 60 * 60 * 24 * 7 * 4;  //4周
                    return response.newBuilder()
                            .header("Cache-Control", "public,only-if-cached,max-stale=" + maxStale)
                            .removeHeader("Pragma").build();
                }
            }
        };
    
    
        Interceptor mHeaderInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request.Builder builder = originalRequest.newBuilder();
                //设置具体的Head内容
                builder.header("timestamp", System.currentTimeMillis() + "");
                Request.Builder requestBuilder =
                        builder.method(originalRequest.method(), originalRequest.body());
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        };
    }
    
    

    ApiConstants网络接口常量

    package com.wj.rxcode.api;
    
    /**
     * Created by wj on 2017/11/17 13:23.
     */
    
    public class ApiConstants {
    
        //好奇心日报
        public static final String API_SERVER = "http://app3.qdaily.com/";
    
        //http://app3.qdaily.com/app3/papers/detail/2014.json
        public static final String API_PAPERS_DETAIL="app3/papers/detail/2014.json";
    }
    
    

    ApiService接口

    package com.wj.rxcode.api;
    
    
    import com.wj.rxcode.bean.PapersDetailBean;
    
    import io.reactivex.Observable;
    import retrofit2.http.GET;
    
    
    public interface ApiService {
    
        @GET(ApiConstants.API_PAPERS_DETAIL)
        Observable<PapersDetailBean> getPaperDetail();
    
    }
    
    

    二、使用

    package com.wj.rxcode;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    
    import com.wj.rxcode.api.ApiRetrofit;
    import com.wj.rxcode.api.ApiService;
    import com.wj.rxcode.bean.PapersDetailBean;
    
    import io.reactivex.Observable;
    import io.reactivex.Observer;
    import io.reactivex.android.schedulers.AndroidSchedulers;
    import io.reactivex.disposables.Disposable;
    import io.reactivex.schedulers.Schedulers;
    
    public class MainActivity extends AppCompatActivity {
    
        private ApiService apiService;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            apiService = ApiRetrofit.getInstance().getApiService();
    
            getPaperDetail();
    
        }
    
    
        private void getPaperDetail(){
    
            Observer<PapersDetailBean> observer= new Observer<PapersDetailBean>() {
    
                //开始请求
                @Override
                public void onSubscribe(Disposable d) {
                    Log.i("RxJava","开始请求");
                }
    
                //请求完成
                @Override
                public void onComplete() {
                    Log.i("RxJava","请求完成");
                }
    
                //请求失败
                @Override
                public void onError(Throwable e) {
                    Log.i("RxJava","请求失败");
                }
    
                //请求成功
                @Override
                public void onNext(PapersDetailBean bean) {
                    Log.i("RxJava","请求成功");
                }
            };
    
            Observable<PapersDetailBean> paperDetail = apiService.getPaperDetail();
            paperDetail.subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:Retrofit 探索二:RxJava+Retrofit实现网络

          本文链接:https://www.haomeiwen.com/subject/jzejvxtx.html