anber
anber

Reputation: 3655

Retrofit headers interceptor does not change header

I have android app with few api calls. I noticed that every call has @Headers("Content-Type: application/json") annotation in ApiService so I decided remove annotation and add header via interceptor to all requests:

    val headers = { chain: Interceptor.Chain ->
        val request = chain.request().newBuilder()
                .addHeader("Content-Type", "application/json")
                .build()
        chain.proceed(request)
    }

    val logging = HttpLoggingInterceptor()
    logging.level = HttpLoggingInterceptor.Level.BODY

    val client = OkHttpClient.Builder()
            .addInterceptor(headers)
            .addInterceptor(logging)
            .build()

    val customGson = GsonBuilder()
            .registerTypeAdapter(NameValuesList::class.java, NamesValuesListConverter())
            .create()

    val retrofit = Retrofit.Builder()
            .baseUrl("http://www.$fullDomain")
            .addConverterFactory(GsonConverterFactory.create(customGson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(client)
            .build()

    service = retrofit.create(ApiService::class.java)

But after that server return error on api call. In logs I see that when I have explicit @Headers() annotation:

D/OkHttp: Content-Type: application/json

And after replace it with interceptor:

D/OkHttp: Content-Type: application/json; charset=UTF-8

I tried to change interceptor to this one:

    val headers = { chain: Interceptor.Chain ->
        val request = chain.request().newBuilder()
                .headers(Headers.of(mutableMapOf("Content-Type" to "test")))
                .build()
        chain.proceed(request)
    }

But I still see this in log:

D/OkHttp: Content-Type: application/json; charset=UTF-8

So looks like my interceptor does not apply or overridden. How to fix it?

UPD. I found the reason: when I add GsonConverterFactory it automatically add header Content-Type: application/json; charset=UTF-8. Are there any way to avoid it without implementing custom ConverterFactory?

Upvotes: 2

Views: 2390

Answers (3)

GMM
GMM

Reputation: 41

You can check if header exist.

val headers = { chain: Interceptor.Chain ->
    val request = chain.request().newBuilder()
    if(chain.request().header("Content-Type") == null){
        request.addHeader("Content-Type", "application/json")
    }
    chain.proceed(request.build())
}

Upvotes: 1

Mohd Danish
Mohd Danish

Reputation: 204

Try this

chain.request().newBuilder().removeHeader("Content-Type") .headers(Headers.of(mutableMapOf("Content-Type" to "test"))) .build()

Upvotes: 0

Antonis Radz
Antonis Radz

Reputation: 3097

as documentation says : "Note: Headers do not overwrite each other. All headers with the same name will be included in the request."

refer to retrofit Headers

Upvotes: 1

Related Questions