Hanbit the Developer

[Retrofit2 / OkHttpClient] Send Post Request With JWT(Bearer) Token 본문

Mobile/Android

[Retrofit2 / OkHttpClient] Send Post Request With JWT(Bearer) Token

hanbikan 2021. 7. 21. 21:37
val token = "###Your Token Here###"

// Initialize Network Interceptor
val networkInterceptor = Interceptor { chain ->
    val newRequest = chain.request().newBuilder()
        .addHeader("Authorization", "Bearer $token")
        .build()
    val response = chain.proceed(newRequest)

    response.newBuilder().build()
}

// Build OkHttpClient
val client = OkHttpClient.Builder()
    .addNetworkInterceptor(networkInterceptor)
    .build()

// Build Retrofit
val retrofit = Retrofit.Builder()
    .baseUrl("###URL###")
    .client(client)
    .addConverterFactory(GsonConverterFactory.create())
    .build()

// Create Retrofit, Request Api Call
val call = retrofit.create(ServerApi::class.java).###POST_FUNCTION(PARAM)###
call.enqueue(object: Callback<AccountProfileLookupResponseDto> {
    override fun onResponse(
        call: Call<AccountProfileLookupResponseDto>,
        response: Response<AccountProfileLookupResponseDto>
    ) {
    	// TODO
    }

    override fun onFailure(call: Call<AccountProfileLookupResponseDto>, t: Throwable) {
        Log.e("Api Call Error", t.message.toString())
    }
})

 

You can add headers using OkHttp!

Set your NetworkInterceptor and add it to OkHttpClient, then build Retrofit with the client. It's simple.