Hanbit the Developer
[Retrofit2 / OkHttpClient] Send Post Request With JWT(Bearer) Token 본문
Android
[Retrofit2 / OkHttpClient] Send Post Request With JWT(Bearer) Token
hanbikan 2021. 7. 21. 21:37val 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.
'Android' 카테고리의 다른 글
[Kotlin] TextView의 더보기 기능 구현 (0) | 2021.08.08 |
---|---|
[Retrofit2] Send Post Request With Empty Body (0) | 2021.07.21 |
[kakaomap] 현재 위치 마커 커스텀 이미지로 변경하기 (0) | 2021.07.09 |
[Kotlin] "전화하기" 기능 구현(4줄) (0) | 2021.07.02 |
[Kotlin] Send Get-Request to api server And Get Response Using retrofit2 (0) | 2021.05.28 |