我在 Android 应用程序中使用 Retrofit。当我使用令牌访问 API 以获取用户信息时,它会提供缓存的(先前的)响应。每当我注销并再次登录时,API 都会提供以前的用户详细信息,我在 Postman 中测试了 API,它在那里工作正常。
我尝试了一些我搜索过的解决方案,但没有任何效果。
我得到的响应头是
传输编码:分块内容类型:应用程序/json;charset=utf-8 服务器:Kestrel 日期:2018 年 1 月 8 日星期一 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;
}
}
Run Code Online (Sandbox Code Playgroud)
在您的httpClient拦截器中,尝试添加缓存控制标头:
.addHeader("Cache-control", "no-cache");
Run Code Online (Sandbox Code Playgroud)
编辑
刚注意到你在 Retrofit2
original.newBuilder().header("Cache-control", "no-cache");
Run Code Online (Sandbox Code Playgroud)
或者尝试将其作为注释添加到您的 API 方法中:
@Headers("Cache-control: no-cache")
Response callApi();
Run Code Online (Sandbox Code Playgroud)
根据文档。
编辑 2
好的,我怀疑这是因为您的if条件,authRetrofit如果条件失败,您将不会更新。尝试删除它
if (authRetrofit == null)
帮助这有帮助。
| 归档时间: |
|
| 查看次数: |
2251 次 |
| 最近记录: |