簡體   English   中英

OkHttp從緩存中排除API

[英]OkHttp exclude APIs from caching

我正在使用Retrofit和OkHttp客戶端進行網絡調用。 我的服務器支持Etag緩存,並且已將緩存添加到okHttp client中。 有一些我不想緩存的API

這是我的okHttpClient配置

    OkHttpClient okHttpClient(Context context,
                                         HttpLoggingInterceptor loggingInterceptor,Cache okHttpCache) {
            final OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .cache(okHttpCache)
            return builder.build();
        }


    Cache cache(Context context) {
    return new Cache(new File(context.getCacheDir(), "cache"),10 * 1024 * 1024);
     }

我可以忽略某些API進行緩存嗎?

如果僅使用OkHttp庫,則可以將緩存控制策略指定為請求對象的CacheControl.FORCE_NETWORK 更多信息在這里: https : //github.com/square/okhttp/issues/1496

如果將OkHttp與Retrofit結合使用,則可以在接口內的請求定義方法中添加Cache-Control: no-cache標頭:(示例中拼寫已更新)

@Headers("Cache-Control: no-cache")
@GET("users/me")
Call<User> getUser();

Okhttp3為緩存中的url請求提供一個迭代器

public Iterator<String> urls() throws IOException {
  hasNext();
  next();
  remove();
}

您可以簡單地使用它來檢查感興趣的API並忽略它。 參見文檔http://java.sun.com/javase/6/docs/api/java/util/Iterator.html?is-external=true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM