Retrofit is returning cached response

2019-06-11 07:38发布

问题:

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.

Response header that I am getting is

Transfer-Encoding: chunked Content-Type: application/json; charset=utf-8 Server: Kestrel Date: Mon, 08 Jan 2018 09:35:26 GMT

Below is ApiClient class

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;
}

}

回答1:

In your httpClient interceptor, try adding cache control header:

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

EDIT

Just noticed you are on Retrofit2

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

Alternatively try adding it as an annotation to your API method:

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

According to Docs.

EDIT 2

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)

Help this helps.



回答2:

Use Post request instead, I've faced the same problem, rectified by changing my GET method to post and send one random string as a Field.