java 使用Retrofit 1.9 + OkHttp 2.2进行Android响应缓存

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 使用Retrofit 1.9 + OkHttp 2.2进行Android响应缓存相关的知识,希望对你有一定的参考价值。

#### Android REST Controller with Cache-Control

Android REST Controller with Simple Cache Control Headers using
Retrofit 1.9.0 + OkHttp 2.2.0
public abstract class RestController {
    private static Context mContext;
    private static long SIZE_OF_CACHE = 10 * 1024 * 1024; // 10 MB

    protected static RestAdapter mRestAdapter;

    public static void init(final Context context, String baseAPIUrl) {
        mContext = context;

        // Create Cache
        Cache cache = null;
        try {
            cache = new Cache(new File(mContext.getCacheDir(), "http"), SIZE_OF_CACHE);
        } catch (IOException e) {
            Log.e(RestController.class.getSimpleName(), "Could not create Cache!", e);
        }

        // Create OkHttpClient
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setCache(cache);
        okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
        okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);

        // Add Cache-Control Interceptor
        okHttpClient.networkInterceptors().add(mCacheControlInterceptor);

        // Create Executor
        Executor executor = Executors.newCachedThreadPool();

        mRestAdapter = new RestAdapter.Builder()
                .setEndpoint(baseAPIUrl)
                .setExecutors(executor, executor)
                .setClient(new OkClient(okHttpClient))
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .build();
    }

    private static final Interceptor mCacheControlInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            // Add Cache Control only for GET methods
            if (request.method().equals("GET")) {
                if (ConnectivityHelper.isNetworkAvailable(mContext)) {
                    // 1 day
                    request.newBuilder()
                            .header("Cache-Control", "only-if-cached")
                            .build();
                } else {
                    // 4 weeks stale
                    request.newBuilder()
                            .header("Cache-Control", "public, max-stale=2419200")
                            .build();
                }
            }

            Response response = chain.proceed(request);

            // Re-write response CC header to force use of cache
            return response.newBuilder()
                    .header("Cache-Control", "public, max-age=86400") // 1 day
                    .build();
        }
    };
}

以上是关于java 使用Retrofit 1.9 + OkHttp 2.2进行Android响应缓存的主要内容,如果未能解决你的问题,请参考以下文章

Android Retrofit POJO模型

Android 初探Retrofit2.0.1(最新版)

java.lang.NoClassDefFoundError: retrofit2.Retrofit$Builder Fabric 初始化

java 使用Retrofit / OkHttp轻松处理Cookies

Retrofit基本使用

使用 OkhttpClient 3.2 和 Retrofit 2 发送视频时出现 java.net.SocketTimeoutException