Search code examples
androidkotlinretrofit2

Request headers blank / cannot get via interceptor


I wanted to see the headers generated by Retrofit, so I added an interceptor:

Injected by Hilt:

@Module
@InstallIn(SingletonComponent::class)
internal object NetworkModule {

    @Provides
    @Singleton
    fun provideRetrofit(): Retrofit =
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(
                OkHttpClient.Builder()
                    .cookieJar(SessionCookieJar())
                    .addInterceptor { chain ->
                        chain.request().also { request ->
                            val buffer = Buffer().also { request.body()?.writeTo(it) }
                            Log.d(TAG, "Intercepted request:")
                            Log.d(TAG, request.headers().toString())
                            Log.d(TAG, buffer.readUtf8())
                        }.let(chain::proceed)
                    }
                    .build()
            )
            .addConverterFactory(JsoupConverterFactory())
            .build()

    @Provides
    @Singleton
    fun provideApiService(retrofit: Retrofit): ApiService =
        retrofit.create(ApiService::class.java)
}

Here is the called method:

    @FormUrlEncoded
    @POST("/alswww2.dll/{sessionObject}")
    suspend fun login(
        @Path("sessionObject") sessionObject: String,
        @FieldMap formInputs: Map<String, String>,
    ): Response<ResponseBody>

The logs perfectly show all the form arguments in the body, but there are no headers. I tried .toMultimap() but that gave {} for the headers. Even if Retrofit wouldn't generate any header automatically, what I don't think, at least there must be the one generated by @FormUrlEncoded, or not?


Solution

  • I usually always use Logging Interceptor. It has level HEADERS, that can help you