Retrofit 2.0.2:如何缓存GET请求?

时间:2016-05-26 03:35:48

标签: android retrofit2

我正在尝试缓存我的get请求。对于改造2看起来我不必使用OKHttp。我怎么才能缓存呢?我这样想:

private static Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(BASE_URL /*+ API*/)
            .cache(new Cache(App.sApp.getCacheDir(), 10 * 1024 * 1024)) // 10 MB
            .addInterceptor(new Interceptor() {
                @Override public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    if (ApiUtils.isNetworkAvailable()) {
                        request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
                    } else {
                        request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
                    }
                    return chain.proceed(request);
                }
            })
            .addConverterFactory(GsonConverterFactory.create(getGson()));

但它没有发生。

2 个答案:

答案 0 :(得分:1)

我在{strong> GDGAhmedab​​ad Repo

中的Retrofit2演示中找到了 OkClientFactory

也许它会帮助你。

public class OkClientFactory {
    // Cache size for the OkHttpClient

    private static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB

    private OkClientFactory() {
    }

    @NonNull
    public static OkHttpClient provideOkHttpClient(Application app) {
        // Install an HTTP cache in the application cache directory.
        File cacheDir = new File(app.getCacheDir(), "http");
        Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);

        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .cache(cache);
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.interceptors().add(loggingInterceptor);
        }
        return builder.build();
    } }

现在您可以使用:

.client(App.getInstance().getOkHttpClient())

有关详情,请参阅here

谢谢。

答案 1 :(得分:0)

您需要指定只想缓存GET请求。

public class CachingControlInterceptor implements 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 (ConnectivityUtil.checkConnectivity(getContext())) {
            // 1 day
            request = request.newBuilder()
                .header("Cache-Control", "only-if-cached")
                .build();
        } else {
            // 4 weeks stale
            request = request.newBuilder()
                .header("Cache-Control", "public, max-stale=2419200")
                .build();
        }
    }

    Response originalResponse = chain.proceed(request);
    return originalResponse.newBuilder()
        .header("Cache-Control", "max-age=600")
        .build();
}
}