Search code examples
kotlinhttp-headersretrofit2okhttp

Okhttp interceptor doesn't see request's Content-type header


I need to create an OkHttp interceptor which reads value of request's Content-Type header (POST request with body). Unfortunately, when I try to access it by request.headers, it's not there (I could see other custom headers, but not Content-Type). Yet, I could clearly see it in logs from HttpLoggingInterceptor.

I'm using Retrofit

Sample code:

//versions:
//okHttp: 4.10.0
//retrofit: 2.9.0

interface API {
    @Headers("secret: aaa", "aaa: AAA", "bbb: BBB", "Content-Type: application/json")
    @POST("/post")
    suspend fun echoPOST(@Body bodyData: BodyData): Response<String>
}

data class BodyData(val secret: String = "aaaa", val nonsecret: String = "bbb")

val httpClient = OkHttpClient.Builder()
            .addInterceptor(
                HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
            )
            .addInterceptor(MyInterceptor())
            .build()
val testRetrofitClient = Retrofit.Builder()
            .baseUrl("https://httpbin.org")
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient)
            .build()

val api = testRetrofitClient.create(API::class.java)

suspend fun testRequestPOST() {
        try {
            val response = api.echoPOST(BodyData())
        } catch (e: Exception) {
            Timber.e(e)
        }
}

interceptor:

class MyInterceptor : Interceptor {
    override fun intercept(chain: Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        Log.d("HTTP", "Content-Type: ${request.header("Content-Type")}")
        Log.d("HTTP", "request headers: ${request.headers.joinToString { it.first }}")
        return response
    }
}

when call is triggered, Logcat shows:

// output from HttpLoggingInterceptor
--> POST https://httpbin.org/post
Content-Type: application/json; charset=UTF-8
Content-Length: 35
secret: aaa
bbb: bbb123
ccc: ccc123
{"nonsecret":"bbb","secret":"aaaa"}

// output from MyInterceptor
Content-Type: null
request headers: secret, bbb, ccc

So Content-Type header is present in request (as logged by HttpLoggingInterceptor) but it's not visible in MyInterceptor

What am I doing wrong ?


Solution

  • Look at the RequestBody, which has this information.