改造返回缓存的响应 [英] Retrofit is returning cached response
问题描述
我正在Android应用程序中使用Retrofit.当我使用令牌访问API来获取用户信息时,它会给出已缓存的(先前)响应.每当我注销并再次登录时,API都会提供以前的用户详细信息,我在Postman中对API进行了测试,在此可以正常工作.
I am using Retrofit in an Android application. When I hit an API with token to get user information it gives cached(previous) response. Whenever I logged out and log in again API gives previous user detail, I tested API in Postman it works fine there.
我尝试了一些搜索过的解决方案,但是没有任何效果.
I have tried some solutions I searched but nothing is working.
我收到的响应标头是
Transfer-Encoding:分块内容类型:application/json;字符集= utf-8服务器:红est日期:2018年1月8日星期一9:35:26 GMT
Transfer-Encoding: chunked Content-Type: application/json; charset=utf-8 Server: Kestrel Date: Mon, 08 Jan 2018 09:35:26 GMT
下面是 ApiClient
类
public class ApiClient {
public static final String BASE_URL = "http://XX.XXX.XXX.XX/api/";
private static Retrofit authRetrofit = null;
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
}
return retrofit;
}
public static Retrofit getAuthorizeClient(final String token) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.addHeader("Authorization", "Bearer " + token)
.addHeader("Cache-control", "no-cache")
.method(original.method(), original.body())
//.cacheControl(CacheControl.FORCE_NETWORK)
.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.cache(null).build();
if (authRetrofit == null) {
authRetrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.client(client).build();
}
return authRetrofit;
}
}
推荐答案
在您的 httpClient
拦截器中,尝试添加缓存控制标头:
In your httpClient
interceptor, try adding cache control header:
.addHeader("Cache-control", "no-cache");
编辑
只是注意到您正在使用 Retrofit2
Just noticed you are on Retrofit2
original.newBuilder().header("Cache-control", "no-cache");
或者尝试将其作为注释添加到您的API方法中:
Alternatively try adding it as an annotation to your API method:
@Headers("Cache-control: no-cache")
Response callApi();
根据文档.
编辑2
好的,我怀疑是由于您的 if
条件,如果条件失败,您的 authRetrofit
不会被更新.尝试将其删除
Okay I suspect it's because of your if
condition, your authRetrofit
wouldn't be updated if condition failed. Try removing it
if(authRetrofit == null)
帮助这有帮助.
这篇关于改造返回缓存的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!