Android Retrofit 2, differences between addInterceptor & addNetworkInterceptor for editing responses Android Retrofit 2, differences between addInterceptor & addNetworkInterceptor for editing responses android android

Android Retrofit 2, differences between addInterceptor & addNetworkInterceptor for editing responses


The differences are in the names. NetworkInterceptor hooks in at the network level and is an ideal place to put retry logic and anything that doesn't rely on the actual content of the response.

If what you do depends on the contents of the response (like in your case), using a ApplicationInterceptor is more useful, as it gives you the response after it's been processed by any other moving parts you may have such as a JSON deserializer. Otherwise you would have to implement the JSON deserializing yourself inside the NetworkInterceptor which doesn't make much sense considering it's done for you by Retrofit.

Clarification

Square have this useful diagram on their wiki that shows where each type of interceptor sits

interceptor diagram

Thus, the reason you receive a readable string in the ApplicationInterceptor is because Square are trying to de-couple the purposes of the two interceptor types. They don't think you should be making any application dependent decisions in the NetworkInterceptor, and so they don't provide an easy way for you to access the response string. It is possible to get ahold of, but like I said, they don't want you to make decisions that depend on the content of the response - rather, they want you to make decisions based or the network state, or headers etc.

The ApplicationInterceptor is where they want you to make decisions dependent upon the contents of the response, so they provide easier methods to access the content of the response so that you can make informed decisions to retry, or as they detail in their wiki, rewrite responses (which I believe is what you're trying to do).


According to @square:

Each interceptor chain has relative merits.

Application interceptors

  • Don’t need to worry about intermediate responses like redirects and retries.

  • Are always invoked once, even if the HTTP response is served from the cache.

  • Observe the application’s original intent. Unconcerned with OkHttp-injected headers like If-None-Match.

  • Permitted to short-circuit and not call Chain.proceed().

  • Permitted to retry and make multiple calls to Chain.proceed().

  • Can adjust Call timeouts using withConnectTimeout, withReadTimeout, withWriteTimeout.

Network Interceptors

  • Able to operate on intermediate responses like redirects and retries.
  • Not invoked for cached responses that short-circuit the network.
  • Observe the data just as it will be transmitted over the network.
  • Access to the Connection that carries the request.