If-None-Match 没有在我的请求中通过
Posted
技术标签:
【中文标题】If-None-Match 没有在我的请求中通过【英文标题】:If-None-Match doesn't get passed in my request 【发布时间】:2016-06-24 16:47:29 【问题描述】:我已经看到关于这个主题的长时间讨论,并且声称它已在 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-None-Match 对其进行了测试,缓存有效并且预期响应。所以我使用的库版本肯定有问题,或者我的代码有问题。
这里我正在设置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;
寻找一些快速有效的响应,因为我已经花费了合理的时间来寻找解决方案,但没有运气。
谢谢
【问题讨论】:
你能解决这个问题@user3242176 吗?我也面临同样的问题。 【参考方案1】:您的代码似乎可以正常工作,我还没有尝试过,但几周前我遇到了同样的问题。原来是因为改造的日志没有显示 if-none-match 标头。但是当我尝试使用代理拦截请求并首先将请求重定向到我的笔记本电脑时(我使用的是mitmproxy
应用程序),出现了 if-none-match 标头。
无论如何,如果你在这个方法private CacheStrategy getCandidate()
中查看/okhttp3/internal/http/CacheStrategy.java
,你会发现 OkHttp3 实际上正确地使用了 etag & if-none-match 标头。
希望这可以澄清。
【讨论】:
以上是关于If-None-Match 没有在我的请求中通过的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Python 中通过我自己的 GUI 应用程序创建 linux 用户?
ETag 和 If-None-Match HTTP 标头不起作用