So, my goal is to embed the api key
into my Retrofit
object so that I don't need to manually append it as query parameter inside each request function, then I did the following (learn from: https://proandroiddev.com/headers-in-retrofit-a8d71ede2f3e):
private val interceptor = Interceptor { chain ->
val newRequest = chain.request().newBuilder().run {
addHeader("api_key", Constants.API_KEY)
build()
}
chain.proceed(newRequest)
}
private val okHttpClient = OkHttpClient.Builder().run {
connectTimeout(15, TimeUnit.SECONDS)
readTimeout(15, TimeUnit.SECONDS)
addInterceptor(interceptor) //<- apply Interceptor
build()
}
//apply the okHttpClient to my Retrofit object...
But it failed and gave this error: HTTP 403 Forbidden
.
PS: Before adding this Interceptor
everything works fine
Before:
@GET("neo/rest/v1/feed")
suspend fun getAsteroidsResult(
@Query("start_date") startDate: String,
@Query("end_date") endDate: String,
@Query("api_key") apiKey: String = Constants.API_KEY
): ResponseBody
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…