Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

Android Retrofit OkHttpClient Interceptor Add Header Gets Error "HTTP 403 Forbidden"

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...