AnswerBun.com

OkHttpClient doesn't add headers to requests

Stack Overflow Asked by Ghaylen on December 21, 2020

I m creating an android app and i m using retrofit to consume api webservices. my problem is when i add a header using annotation, it works.

@Headers("Authorization: jwt-token")
@POST("appusers-service/signin/identification")
suspend fun authentication(@Body body : LoginIdentificationDto.Params) : NetworkResponse<LoginIdentificationDto.Result, LoginIdentificationDto.Errors>

but when I use intercepters to add the header dynamically, it doesn’t work

@Provides
@Singleton
fun provideHttpClient() : OkHttpClient
{
    return OkHttpClient.Builder()
        .callTimeout(60, TimeUnit.SECONDS)
        .readTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .addNetworkInterceptor {
            
            val builder : Request.Builder = it.request().newBuilder()
            
            builder.addHeader(AUTHORIZATION_HEADER, "jwt-token")
            
            [email protected] it.proceed(builder.build())
        }
        .build()
}

@Provides
@Singleton
fun provideRetrofit(httpClient : OkHttpClient, mapper : ObjectMapper) : Retrofit
{
    return Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(httpClient)
        .addCallAdapterFactory(NetworkResponseAdapterFactory())
        .addConverterFactory(JacksonConverterFactory.create(mapper))
        .build()
}

how can i solve this problem please?

2 Answers

The way I'm doing is to have a class AuthInterceptor

class AuthInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val authenticatedRequest = request.newBuilder()
            .addHeader("Content-Type", "application/json")
            .addHeader("Authorization", UserData.getAuthToken())
            .build()
        return chain.proceed(authenticatedRequest)
    }
}

And on your OkHtttpClient use like this.

val ohHttpClient = OkHttpClient.Builder()
ohHttpClient.addInterceptor(AuthInterceptor())

Answered by Emilio Hoffmann on December 21, 2020

Try this one

return OkHttpClient.Builder()
        .callTimeout(60, TimeUnit.SECONDS)
        .readTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .addInterceptor {
            val builder : Request.Builder = it.request().newBuilder()
            builder.addHeader(AUTHORIZATION_HEADER, "jwt-token")
            [email protected] it.proceed(builder.build())
        }
        .build() 

Note that I have changed addNetworkInterceptor into addInterceptor. For more information you can refer to this answer https://stackoverflow.com/a/37120830/9394700

Answered by mirsaidoff on December 21, 2020

Add your own answers!

Related Questions

Change null to 0 in response

1  Asked on December 3, 2021 by edwin-landsfield

   

Print complete SQL for all queries made by objection.js

2  Asked on December 3, 2021 by eugene-kim

 

Easiest way to convert a char* of hex to actual hex in C?

1  Asked on December 3, 2021 by purplespark

 

Xcode confused with IQAir Api Parsing

1  Asked on December 3, 2021 by unkowncoder

       

gRPC server cannot be built and throws error

0  Asked on December 3, 2021 by jibo_libin

   

How to correctly map huge json file to Java (pojo)?

1  Asked on December 3, 2021 by orkhan-hasanli

     

check all items in csv column except one [python pandas]

2  Asked on December 2, 2021 by blindside044

       

Unpivot a single into two rows – T-SQL

1  Asked on December 2, 2021 by error-1004

       

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir