You're viewing documentation for a version of this software that is in development. Switch to the latest stable version
Launch Apollo Studio

HTTP interceptors


Apollo Android supports multi platform HttpInterceptor very similar to OkHttp Interceptors. Use them to add authentication headers, log the network calls or anything else.

The interface is a single method. For an example, implementing an authentication interceptors can be done with:

class AuthorizationInterceptor(val token: String) : HttpInterceptor {
  override suspend fun intercept(request: HttpRequest,  chain: HttpInterceptorChain): HttpResponse {
    return chain.proceed(request.newBuilder().addHeader("Authorization", "Bearer $token").build())
  }
}

Then add the interceptor to your HttpNetworkTransport:

val apolloClient = ApolloClient.Builder()
    .networkTransport(
        HttpNetworkTransport(
            serverUrl = "https://",
            interceptors = listOf(AuthorizationInterceptor(token))
        )
    )
    .build()

By default, Apollo Android comes with ClientAwarenessInterceptor and LoggingInterceptor.

Reusing OkHttp interceptors on JVM only projects

If your project is a JVM only project and you already have an OkHttp Interceptor, you can also reuse it:

val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(interceptor)
    .build()

val apolloClient = ApolloClient.Builder()
    .networkTransport(
        HttpNetworkTransport(
            serverUrl = "https://",
            engine = DefaultHttpEngine(okHttpClient)
        )
    )
    .build()
Edit on GitHub