简体   繁体   English

使用retrofit2和okhttp3缓存请求

[英]Cache requests using retrofit2 and okhttp3

I am using retrofit2 to cash responses using cache interceptor 我正在使用retrofit2来使用缓存拦截器来兑现响应

 @Override
public Response intercept(Chain chain) throws IOException {
    Response originalResponse = chain.proceed(chain.request());
    if (NetworkUtil.isConnected(context)) {
        return originalResponse.newBuilder()
                .header("Cache-Control", "public, max-age=" + MAX_AGE)
                .build();
    } else {
        return originalResponse.newBuilder()
                .header("Cache-Control", "public, only-if-cached, max-stale=" + MAX_STALE)
                .build();
    }
}

but i need to cache specific requests not all of it, how to do that? 但我需要缓存特定的请求而不是全部,如何做到这一点?

public Response intercept(Chain chain)

The chain here contains the request that is being made. 这里的链包含正在进行的请求。

public Response intercept(Chain chain) {
    Request request = chain.request()
}

You can inspect this request and act on the info, for example with request.url() and request.headers() . 您可以检查此请求并对信息进行操作,例如使用request.url()request.headers()

See more about intercepting here . 在此处查看有关拦截的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM