Retrofit2 automatically removes the header with the content type

Viewed 42

I'm trying to send a POST request with a body and two headers: a cookie and a content type

In the chuckerinterceptor, I see that the header with the content type is lost in the request, I found information that okhttp automatically deletes the header if the body is empty, but I see that my body is not empty.

I tried to add an annotation and an interceptor, in both cases the header disappears

@Singleton
@Provides
@Named("rkkFilter")
fun rkkFilter(@ApplicationContext context: Context): rkkFilter =
    Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(
            OkHttpClient().newBuilder()
                .addInterceptor(ChuckerInterceptor(context)).build()
                //.addInterceptor(CookieInterceptor(context)).build()
         )
        .addConverterFactory(
            GsonConverterFactory.create(
                GsonBuilder()
                    .setLenient()
                    .create()
            )
        )
        .build()
        .create(
            rkkFilter::class.java
        )

Cookie Interceptor:

class CookieInterceptor(context: Context) : Interceptor {
    val context: Context = context
    override fun intercept(chain: Interceptor.Chain): Response {
        val builder: Request.Builder = chain.request().newBuilder()
        val pref: SharedPreferences = context.getSharedPreferences(
            "prefs",
            ComponentActivity.MODE_PRIVATE
        )
        builder.addHeader("Cookie", pref.getString("id", "NOVALUE"))
        builder.addHeader("Content-Type", "application/json; charset=utf-8")
        return chain.proceed(builder.build())
    }
}

interface rkkFilter

interface rkkFilter {
    @POST("rkk/filter")
    suspend fun filterRkk(
        @Body rkkFilter: RkkFilter
    ): Response<ResponseBody>
}

I dont understand wheres error, i tried to debug all request but didnt find anything

Original Request

1 Answers

Remove .build() from this line .addInterceptor(ChuckerInterceptor(context)).build() so now your code looks like this.

OkHttpClient().newBuilder()
            .addInterceptor(ChuckerInterceptor(context))
            .addInterceptor(CookieInterceptor(context)).build()
Related