Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ internal constructor(
private var sslSocketFactory: SSLSocketFactory? = null
private var trustManager: X509TrustManager? = null
private var hostnameVerifier: HostnameVerifier? = null
private val interceptors: MutableList<okhttp3.Interceptor> = mutableListOf()

fun timeout(timeout: Timeout) = apply { this.timeout = timeout }

Expand Down Expand Up @@ -279,6 +280,33 @@ internal constructor(
this.hostnameVerifier = hostnameVerifier
}

/**
* Adds a custom OkHttp [okhttp3.Interceptor] that will be applied to every request.
*
* This is useful for cross-cutting concerns such as trace context propagation. For example,
* to forward an `X-Trace-Id` header from an incoming request using a [ThreadLocal]:
*
* ```kotlin
* val traceIdHolder = ThreadLocal<String>()
*
* val httpClient = OkHttpClient.builder()
* .backend(backend)
* .addInterceptor { chain ->
* val traceId = traceIdHolder.get()
* val request = if (traceId != null) {
* chain.request().newBuilder().addHeader("X-Trace-Id", traceId).build()
* } else {
* chain.request()
* }
* chain.proceed(request)
* }
* .build()
* ```
*/
fun addInterceptor(interceptor: okhttp3.Interceptor) = apply {
interceptors.add(interceptor)
}

fun build(): OkHttpClient =
OkHttpClient(
okhttp3.OkHttpClient.Builder()
Expand Down Expand Up @@ -320,6 +348,8 @@ internal constructor(
}

hostnameVerifier?.let(::hostnameVerifier)

interceptors.forEach { addInterceptor(it) }
}
.build()
.apply {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,43 @@ internal class OkHttpClientTest {
httpClient = OkHttpClient.builder().backend(TestBackend(baseUrl)).build()
}

@Test
fun addInterceptor_interceptorIsCalledAndCanAddHeaders() {
stubFor(post(urlPathEqualTo("/something")).willReturn(ok()))
val traceIdHolder = ThreadLocal<String>()
val clientWithInterceptor =
OkHttpClient.builder()
.backend(TestBackend(baseUrl))
.addInterceptor { chain ->
val traceId = traceIdHolder.get()
val request =
if (traceId != null) {
chain.request().newBuilder().addHeader("X-Trace-Id", traceId).build()
} else {
chain.request()
}
chain.proceed(request)
}
.build()

traceIdHolder.set("test-trace-123")
try {
clientWithInterceptor
.execute(
HttpRequest.builder()
.method(HttpMethod.POST)
.baseUrl(baseUrl)
.addPathSegment("something")
.build()
)
.close()
} finally {
traceIdHolder.remove()
}

verify(postRequestedFor(urlPathEqualTo("/something")).withHeader("X-Trace-Id", equalTo("test-trace-123")))
}

@Test
fun executeAsync_whenFutureCancelled_cancelsUnderlyingCall() {
stubFor(post(urlPathEqualTo("/something")).willReturn(ok()))
Expand Down