Home > Back-end >  Using addHeader() in an interceptor with retrofit doesn't give the right request
Using addHeader() in an interceptor with retrofit doesn't give the right request

Time:09-24

I'm trying to use global headers with a headerInterceptor but when I test it, they don't seem to be working. When I use @Headers("Content-Type: application/json") in the apiService, it works. I've followed several tutorials and I can't find any differences in code.

fun getRetrofit(): Retrofit{
return Retrofit.Builder()
    .baseUrl(BASE_URL)
    .client(client)
    .addConverterFactory(GsonConverterFactory.create())
    .build()
}


private val client = OkHttpClient.Builder()
    .addInterceptor(HeaderInterceptor())
    .build()



class HeaderInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
            .newBuilder()
            .addHeader("Content-Type", "application/json")//This doesn't work
            .build()
        return chain.proceed(request)
    }
}

I call getRetrofit() like this, within a coroutine:

val respuesta = getRetrofit().create(KiritoApiService::class.java).requestMyToken(salida).execute()

The related dependencies I'm using are these:

implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
implementation "com.squareup.okhttp3:logging-interceptor:4.5.0"

I've also tried changing .addHeader() for .header() with no success. I've made it work with @Headers() tags in the @POST requests, but I want this to work, as it's more readable and I can make less mistakes. Many thanks in advance!!

Edit: I'm adding the results of the logging interceptor. They are exactly the same, except for the order between "Content-Type" and "Content-Length". I've also ruled that out with another test, so I think the problem isn't in the headers. I dont know what else can I be missing.

Using @headers("Content-Type: application/json") I get the correct answer from the server:

2022-09-23 14:53:29.599 3829-3888/es.kirito.kirito D/OkHttp: --> POST https://kirito.es/chasca/api.php
2022-09-23 14:53:29.599 3829-3888/es.kirito.kirito D/OkHttp: Content-Type: application/json
2022-09-23 14:53:29.599 3829-3888/es.kirito.kirito D/OkHttp: Content-Length: 156
2022-09-23 14:53:29.600 3829-3888/es.kirito.kirito D/OkHttp: {"descripcion_dispositivo":"AOSP on IA Emulator","id_dispositivo":"78b69555b3082d5a","password":"123456","peticion":"usuarios.login","usuario":"1234567"}
2022-09-23 14:53:29.600 3829-3888/es.kirito.kirito D/OkHttp: --> END POST (156-byte body)
2022-09-23 14:53:29.720 3829-3888/es.kirito.kirito D/OkHttp: <-- 200 https://kirito.es/chasca/api.php (120ms)
2022-09-23 14:53:29.720 3829-3888/es.kirito.kirito D/OkHttp: server: nginx
2022-09-23 14:53:29.720 3829-3888/es.kirito.kirito D/OkHttp: date: Fri, 23 Sep 2022 12:53:31 GMT
2022-09-23 14:53:29.720 3829-3888/es.kirito.kirito D/OkHttp: content-type: application/json; charset=utf-8
2022-09-23 14:53:29.720 3829-3888/es.kirito.kirito D/OkHttp: vary: Accept-Encoding
2022-09-23 14:53:29.720 3829-3888/es.kirito.kirito D/OkHttp: set-cookie: a=8a9935e7a5391b78e6cd3948b4331a3e; path=/chasca/
2022-09-23 14:53:29.720 3829-3888/es.kirito.kirito D/OkHttp: content-security-policy: upgrade-insecure-requests;
2022-09-23 14:53:29.720 3829-3888/es.kirito.kirito D/OkHttp: x-frame-options: SAMEORIGIN
2022-09-23 14:53:29.720 3829-3888/es.kirito.kirito D/OkHttp: x-xss-protection: 1; mode=block
2022-09-23 14:53:29.720 3829-3888/es.kirito.kirito D/OkHttp: strict-transport-security: max-age=31536000; includeSubDomains; preload
2022-09-23 14:53:29.720 3829-3888/es.kirito.kirito D/OkHttp: x-xss-protection: 1; mode=block
2022-09-23 14:53:29.720 3829-3888/es.kirito.kirito D/OkHttp: x-content-type-options: nosniff
2022-09-23 14:53:29.721 3829-3888/es.kirito.kirito D/OkHttp: x-server-powered-by: Engintron
2022-09-23 14:53:29.722 3829-3888/es.kirito.kirito D/OkHttp: {"error":{"error":"0","errorCode":"0","errorDesc":"Sin error"},"query":{"fecha":"23-09-2022","hora":"14:53:31","query":"usuarios.login"},"respuesta":{"login":{"id_usuario":"11","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZF91c3VhcmlvIjoiMTEiLCJwYXRoX2luc3RhbGFjaW9uIjoiY2hhc2NhIn0=.A2OIiiPdVkuZ82xz4RqpfcA2BChl7Kcv9HIVPwAz9IE="}}}
2022-09-23 14:53:29.722 3829-3888/es.kirito.kirito D/OkHttp: <-- END HTTP (336-byte body)

Using the header interceptor .addHeader("Content-Type", "application/json"):

2022-09-23 15:52:59.650 4133-4182/es.kirito.kirito D/OkHttp: --> POST https://kirito.es/chasca/api.php
2022-09-23 15:52:59.650 4133-4182/es.kirito.kirito D/OkHttp: Content-Length: 156
2022-09-23 15:52:59.650 4133-4182/es.kirito.kirito D/OkHttp: Content-Type: application/json
2022-09-23 15:52:59.651 4133-4182/es.kirito.kirito D/OkHttp: {"descripcion_dispositivo":"AOSP on IA Emulator","id_dispositivo":"78b69555b3082d5a","password":"123456","peticion":"usuarios.login","usuario":"1234567"}
2022-09-23 15:52:59.651 4133-4182/es.kirito.kirito D/OkHttp: --> END POST (156-byte body)
2022-09-23 15:52:59.696 4133-4182/es.kirito.kirito D/OkHttp: <-- 200 https://kirito.es/chasca/api.php (44ms)
2022-09-23 15:52:59.696 4133-4182/es.kirito.kirito D/OkHttp: server: nginx
2022-09-23 15:52:59.696 4133-4182/es.kirito.kirito D/OkHttp: date: Fri, 23 Sep 2022 13:53:01 GMT
2022-09-23 15:52:59.696 4133-4182/es.kirito.kirito D/OkHttp: content-type: application/json; charset=utf-8
2022-09-23 15:52:59.696 4133-4182/es.kirito.kirito D/OkHttp: vary: Accept-Encoding
2022-09-23 15:52:59.696 4133-4182/es.kirito.kirito D/OkHttp: set-cookie: a=dc971fbc6b3f5bf05bab74bc1793da5c; path=/chasca/
2022-09-23 15:52:59.696 4133-4182/es.kirito.kirito D/OkHttp: content-security-policy: upgrade-insecure-requests;
2022-09-23 15:52:59.696 4133-4182/es.kirito.kirito D/OkHttp: x-frame-options: SAMEORIGIN
2022-09-23 15:52:59.696 4133-4182/es.kirito.kirito D/OkHttp: x-xss-protection: 1; mode=block
2022-09-23 15:52:59.696 4133-4182/es.kirito.kirito D/OkHttp: strict-transport-security: max-age=31536000; includeSubDomains; preload
2022-09-23 15:52:59.696 4133-4182/es.kirito.kirito D/OkHttp: x-xss-protection: 1; mode=block
2022-09-23 15:52:59.696 4133-4182/es.kirito.kirito D/OkHttp: x-content-type-options: nosniff
2022-09-23 15:52:59.696 4133-4182/es.kirito.kirito D/OkHttp: x-server-powered-by: Engintron
2022-09-23 15:52:59.697 4133-4182/es.kirito.kirito D/OkHttp: {"error":{"error":"1","errorCode":"3","errorDesc":"Peticion incorrecta"},"query":{"fecha":"23-09-2022","hora":"15:53:01","query":null},"respuesta":null}
2022-09-23 15:52:59.697 4133-4182/es.kirito.kirito D/OkHttp: <-- END HTTP (152-byte body)

Final edit: The problem at the end was on the server side. The slight difference is that when I send the headers with the interceptor, it actually sends "application\json; charset=UTF-8", together, and the server didn't recognise then either of the configurations.

CodePudding user response:

How do you know that it doesn't work? Your code seems legit, but there might be some hidden pitfalls after all.

To narrow down the problem, I would suggest to add a logging interceptor additionally (you already have the depencency):

private val client = OkHttpClient.Builder()
    .addInterceptor(HeaderInterceptor())
    .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
    .build()

I reproduced your code on my machine and logging shows me that the header is set as it should be:

I/okhttp.OkHttpClient: Content-Type: application/json

This indicates that the problem might not be with the header. Maybe there is something else wrong with your request. As I said, please add the logger interceptor as described above. Maybe you can share this output here for further debugging.

  • Related