0

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 
Sam Chen
  • 7,597
  • 2
  • 40
  • 73
  • Can you share how the api_key was added before? – eimmer Jul 01 '21 at 14:54
  • Your first approach was adding the api_key as a query parameter. The second approach is adding it as a header. They are not the same. Read more here. https://stackoverflow.com/questions/40492782/what-is-the-difference-between-http-parameters-and-http-headers – eimmer Jul 01 '21 at 19:44
  • @eimmer But what about the article I mentioned? – Sam Chen Jul 01 '21 at 19:50
  • The article only seems to outline how to add a value to the header. Am I missing something relevant? – eimmer Jul 02 '21 at 13:14
  • last I knew you read in values passed in the two different ways differently on the server side. So, you would have to update the server code to read in the headers. – eimmer Jul 09 '21 at 19:20

1 Answers1

0

Could you please add log interceptor and set the log level and provide a log?

 compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'

And sth like this :

 OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
     okBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC).setLevel
             (HttpLoggingInterceptor.Level.BODY).setLevel(HttpLoggingInterceptor.Level.HEADERS))
Dheeraj Gupta
  • 405
  • 1
  • 4
  • 12