2

I see that ResponseInterceptors are present in OkHttp. I would like to use one, but I'm using Retrofit rather than OkHttp directly.

My question is firstly is it possible to use ResponseInterceptors with retrofit? If so how? There's api methods for Request interceptors but I can't find any corresponding Response methods.

aaronmarino
  • 3,723
  • 1
  • 23
  • 36

2 Answers2

3

For anyone who stumbles across this, I managed to find the answer after further searching. Note that the below requires OkHttp 2.2+ and retrofit 1.9+

//First create the OkHttp client and add your response interceptor
OkHttpClient httpClient = new OkHttpClient();
httpClient.interceptors().add(new ApiResponseInterceptor());

//then set the client on your RestAdapter
RestAdapter.Builder builder = new RestAdapter.Builder()
       .setEndpoint(ACCOUNTS_SERVICE_BASE_URL)
       .setClient(new OkClient(httpClient))
       .setConverter(new GsonConverter(gson)) 
       .setRequestInterceptor(getAuthRequestInterceptor())
       .setLogLevel(RestAdapter.LogLevel.FULL); 
aaronmarino
  • 3,723
  • 1
  • 23
  • 36
0

See also this this question, which appears to be a duplicate of this one. One possibility is to override the execute method in Retrofit's OkClient:

OkClient client = new OkClient(okHttpClient) {
    @Override
    public retrofit.client.Response execute(retrofit.client.Request request) throws IOException {
        retrofit.client.Response response = super.execute(request);

        // Inspect 'response' before returning it

        return response;
    }
};

RestAdapter.Builder restAdapterBuilder = new RestAdapter.Builder()
        .setEndpoint(API_BASE_URL)
        .setClient(client);
Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42