首页 > 解决方案 > Android Retrofit OkHttpClient 拦截器添加标头获取错误“HTTP 403 Forbidden”

问题描述

所以,我的目标是将它嵌入api key到我的Retrofit对象中,这样我就不需要在每个请求函数中手动将它作为查询参数附加,然后我做了以下事情(学习:https ://proandroiddev.com/headers-in -改造-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...

但它失败并给出了这个错误:HTTP 403 Forbidden.

PS:在添加之前Interceptor一切正常


前:

@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 

标签: androidretrofitretrofit2okhttp

解决方案


您能否添加日志拦截器并设置日志级别并提供日志?

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

像这样的东西:

 OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
     okBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC).setLevel
             (HttpLoggingInterceptor.Level.BODY).setLevel(HttpLoggingInterceptor.Level.HEADERS))

推荐阅读