我已经看到了关于这个话题的很长一段时间的讨论,并声称它在2.3.0中得到了修复。下面是我使用的组合
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
compile 'com.squareup.okhttp3:okhttp:3.2.0'我在接收到的响应中看到的日志都有Etag;但是我做的后续请求没有在其头中传递If-None Match。我通过在我的代码中显式地插入If- one -Match来测试它,缓存起作用了,response应该是一个。因此,我使用的库的版本肯定有问题,或者我的代码不太好。
我在这里设置okClient。
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
okhttp3.OkHttpClient okClient = new okhttp3.OkHttpClient.Builder()
.addInterceptor(new HeaderInterceptor())
.addInterceptor(httpLoggingInterceptor)
.cache(createCacheForOkHTTP())
.connectTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(AppConfig.API_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okClient)
.build();我的头拦截器包含的逻辑主要集中在API本身。就是这里
private class HeaderInterceptor
implements Interceptor {
private String generateAuthHeader(AuthResponse accessToken) {
if (accessToken == null) {
return "";
}
return String.format("Bearer %s", accessToken.getAccessToken());
}
@Override
public okhttp3.Response intercept(Chain chain)
throws IOException {
Request request = chain.request();
final String authorizationValue = generateAuthHeader(runtime.getPrefAccessToken());
if (!TextUtils.isEmpty(authorizationValue)) {
request = request.newBuilder()
.addHeader(AppConfig.API_KEY_AUTHORIZATION, authorizationValue)
.addHeader(AppConfig.API_KEY_ACCEPT, AppConfig.API_ACCEPT)
.build();
//.addHeader("If-None-Match", "a69385c6d34596e48cdddd3ce475d290")
} else {
request = request.newBuilder()
.addHeader(AppConfig.API_KEY_CONTENT_TYPE, AppConfig.API_CONTENT_TYPE)
.addHeader(AppConfig.API_KEY_ACCEPT, AppConfig.API_ACCEPT)
.build();
}
okhttp3.Response response = chain.proceed(request);
return response;
}
}下面是我用来设置缓存的方法。
private Cache createCacheForOkHTTP() {
Cache cache = null;
cache = new Cache(App.getInstance().getBaseContext().getCacheDir(), 1024 * 1024 * 10);
return cache;
}寻找一些快速和有效的反应,因为我已经花了合理的时间找到解决方案,但没有运气。
谢谢
发布于 2016-09-07 02:03:44
你的代码似乎在工作,我还没有试过,但几周前我遇到了同样的问题。事实证明,这是因为改造的日志没有显示if-none-match标头。但当我尝试使用代理拦截请求并首先将请求重定向到我的笔记本电脑(我正在使用mitmproxy应用程序)时,出现了if-none-match标头。
无论如何,如果您查看此方法private CacheStrategy getCandidate()中的/okhttp3/internal/http/CacheStrategy.java,您将看到OkHttp3实际上正确地使用了etag & if-none-match头。
希望这能澄清。
https://stackoverflow.com/questions/35906361
复制相似问题