Retrofit + RxJava无法缓存响应 - Android

时间:2017-07-26 13:43:59

标签: android retrofit retrofit2 rx-android okhttp3

我在我的项目中使用bellow库来连接服务,然后我从服务中得到一个值列表,然后我用它们填充我的微调器:

compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

问题:如何将我的适配器列表缓存48小时,或者每48小时从服务中更新我的微调器列表。

Bellow是我的RetrofitApi class,但是当我打开应用程序并且无法缓存48小时时调用服务:

public class RetrofitApi {
    private static PublicApi retrofit = null;

    public static PublicApi getClient(String url) {
        OkHttpClient okHttpClient;
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();

                    request = new Request.Builder()
                            .cacheControl(new CacheControl.Builder()
                                    .maxAge(2, TimeUnit.DAYS)
                                    .minFresh(48, TimeUnit.HOURS)
                                    .maxStale(48, TimeUnit.HOURS)
                                    .build())
                            .url(request.url())
                            .build();


                    return chain.proceed(request);
                }
            }).build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build().create(PublicApi.class);

        return retrofit;
    }
}

然后我像bellow一样连接我的服务:

PublicApi publicApi = retrofitApi.getClient("https://xxx.xxx.xxx", context);
mCompositeDisposable.add(publicApi.language("getLanguages")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(language -> responseLanguage(language, resultListener), language -> errorLanguage(language, resultListener)));

2 个答案:

答案 0 :(得分:0)

如果您尝试实现的目标是刷新数据而不是应该避开计时器,那么固定间隔计时器(如电池耗尽)存在一些主要缺点,推送通知等其他解决方案可能更有用,更多信息缺点:

Scheduling Repeating Alarms

如果您仍想使用计时器,可能会有所帮助:

scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

    //Schedule a task to run at fixed rate    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            // Do stuff here!

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // Do stuff to update UI here!
                    Toast.makeText(MainActivity.this, "timer ", Toast.LENGTH_SHORT).show();
                }
            });

        }
    }, 0, 48, TimeUnit.HOURS); 

答案 1 :(得分:0)

解决了我的问题:

import android.content.Context;
import android.os.Build;
import android.util.Log;

import com.bumptech.glide.util.Util;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.File;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import xxx.xxx.xxx.tools.Utils;
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.converter.gson.GsonConverterFactory;

/**
 * Created by admin on 7/11/2017.
 */

public class RetrofitApi {
    private static PublicApi retrofit = null;
    private Context context;


    public PublicApi getClient(String url, Context context, Integer value) {
        OkHttpClient okHttpClient;
        this.context = context;
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            if (value == 1) {
                //For get Log see D/OkHttp
                HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
                // set your desired log level
                logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);
                File httpCacheDirectory = new File(context.getCacheDir(), "responses");
                int cacheSize = 10 * 1024 * 1024; // 10 MiB
                Cache cache = new Cache(httpCacheDirectory, cacheSize);

                if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    okHttpClient = builder.
                            addNetworkInterceptor(REWRITE_RESPONSE_INTERCEPTOR)
                            .addInterceptor(OFFLINE_INTERCEPTOR)
                            .addInterceptor(logging)
                            .cache(cache)
                            .build();
                } else {
                    okHttpClient = new OkHttpClient.Builder()
                            .addNetworkInterceptor(REWRITE_RESPONSE_INTERCEPTOR)
                            .addInterceptor(OFFLINE_INTERCEPTOR)
                            .addInterceptor(logging)
                            .cache(cache)
                            .build();
                }


            } else {
                okHttpClient = builder.build();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(okHttpClient)
                //.client(httpClient.build())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build().create(PublicApi.class);

        return retrofit;
    }

    private Interceptor REWRITE_RESPONSE_INTERCEPTOR = chain -> {
        Response originalResponse = chain.proceed(chain.request());
        String cacheControl = originalResponse.header("Cache-Control");

        if (cacheControl == null || cacheControl.contains("no-store") || cacheControl.contains("no-cache") ||
                cacheControl.contains("must-revalidate") || cacheControl.contains("max-age=0")) {
            return originalResponse.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public, max-age=" + 60)
                    .build();
        } else {
            return originalResponse;
        }
    };


    private Interceptor OFFLINE_INTERCEPTOR = chain -> {
        Request request = chain.request();
        //if (!Utils.isNetworkAvailable(context)) {
        int maxStale = 60 * 60 * 24 * 2; // tolerate 2-days stale
        request = request.newBuilder()
                .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                .build();
        // }

        return chain.proceed(request);
    };
}