Retrofit正在返回缓存的响应

时间:2018-01-07 18:43:40

标签: android retrofit2

我在Android应用程序中使用Retrofit。当我使用令牌获取API以获取用户信息时,它会提供缓存(先前)响应。每当我退出并再次登录时API会提供以前的用户详细信息,我在Postman中测试了API,它在那里工作正常。

我尝试了一些我搜索过的解决方案,但没有任何工作。

我得到的回复标题是

  

转移编码:分块   Content-Type:application / json;字符集= utf-8的   服务器:红隼   日期:星期一,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;
}

}

2 个答案:

答案 0 :(得分:3)

httpClient拦截器中,尝试添加缓存控制标头:

 .addHeader("Cache-control", "no-cache");

修改

注意到你在Retrofit2

original.newBuilder().header("Cache-control", "no-cache");

或者尝试将其作为注释添加到API方法中:

@Headers("Cache-control: no-cache")
Response callApi();

根据Docs.

编辑2

好的,我怀疑是因为你的if条件,如果条件失败,你的authRetrofit就不会被更新。尝试删除它

if (authRetrofit == null)

帮助这有帮助。

答案 1 :(得分:0)

使用Post请求代替,我也遇到了同样的问题,通过更改GET方法以发布并发送一个随机字符串作为Field来纠正。