如何使用注释在改造请求中动态添加授权标头?

时间:2019-04-21 16:48:28

标签: android kotlin retrofit2

实际上,我在Android应用程序中使用Retrofit 2(我在使用Kotlin),并且我想执行如下发布请求:

@Headers("Authorization: Bearer: $Constants.TOKEN")
@POST("/task")
fun createTask(object:Object)

当令牌是一个常数,但是我希望它是动态的时,请求可以完美地工作。

经过多次搜索,我发现了如下解决方案:

@POST("/task")
fun createTask(@Header("Authorization: Bearer") authorization:String, object:Object)

OR

@POST("/task")
fun createTask(@HeaderMap header:Map<String, String>, object:Object)

尝试时,出现类似的错误:

bad request : error at char 0x20 

2 个答案:

答案 0 :(得分:1)

我也面临着同样的问题,但是后来我尝试了类似的事情:

@POST("/task")
fun createTask(@Header("Authorization") authorization, object:Object)

然后将Bearer附加到您要传递的令牌中,例如

createTask("Bearer ".plus(access_token))

另外,似乎您添加的多余冒号:导致了错误,删除冒号也可能起作用。

答案 1 :(得分:1)

要使标头动态化,我在使用翻新时要使用标头拦截器,

class HeaderInterceptor: Interceptor {

/**
 * Interceptor class for setting of the dynamic headers for every request
 */
override fun intercept(chain: Interceptor.Chain): Response {
    var request = chain.request()
    request = request?.newBuilder()
            // dynamic token you get should be use instead of #YOUR_DYNAMIC_TOKEN.
            ?.addHeader("Authorization: Bearer", #YOUR_DYNAMIC_TOKEN)  
            ?.build()
    return chain.proceed(request)
}

}

现在我们可以像下面一样使用它

@Provides
@Singleton
fun getOkHttpClient(): OkHttpClient {
     val interceptor = HttpLoggingInterceptor()
     interceptor.level = HttpLoggingInterceptor.Level.BODY
     val builder = OkHttpClient.Builder()
     builder.addInterceptor(interceptor)
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .addInterceptor(HeaderInterceptor())                
     return builder.build()

}


或者我们可以像这样直接使用它:

@Provides
  @Singleton
  fun getOkHttpClient(): OkHttpClient {
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        val builder = OkHttpClient.Builder()
        builder.addInterceptor(interceptor)
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .followRedirects(true)
                .followSslRedirects(true)
                .addInterceptor { chain ->
                    val newRequest = chain.request().newBuilder()
                            .addHeader("Authorization: Bearer", #YOUR_DYNAMIC_TOKEN)
                            .build()
                    chain.proceed(newRequest)
                }
  }