问题描述
我正在使用 OAuth,每次发出请求时都需要将 OAuth 令牌放入我的标头中.我看到了 @Header
注释,但是有没有办法让它参数化以便我可以在运行时传入?
I am using OAuth and I need to put the OAuth token in my header every time I make a request. I see the @Header
annotation, but is there a way to make it parameterized so i can pass in at run time?
这是一个概念
@Header({授权:'OAuth {var}', api_version={var} })
你能在运行时传递它们吗?
Can you pass them in at Runtime?
@GET("/users")
void getUsers(
@Header("Authorization") String auth,
@Header("X-Api-Version") String version,
Callback<User> callback
)
推荐答案
除了使用@Header 参数之外,我更愿意使用 RequestInterceptor 来更新您的所有请求,而无需更改您的界面.使用类似的东西:
Besides using @Header parameter, I'd rather use RequestInterceptor to update all your request without changing your interface. Using something like:
RestAdapter.Builder builder = new RestAdapter.Builder()
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("Accept", "application/json;versions=1");
if (isUserLoggedIn()) {
request.addHeader("Authorization", getToken());
}
}
});
p/s : 如果你使用的是 Retrofit2,你应该使用 Interceptor
而不是 RequestInterceptor
p/s : If you are using Retrofit2, you should use Interceptor
instead of RequestInterceptor
由于 RequestInterceptor
在 Retrofit 2.0 中不再可用
Since RequestInterceptor
is not longer available in Retrofit 2.0
这篇关于Android Retrofit 参数化@Headers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!