Retrofit2授权-访问令牌的全局拦截器 [英] Retrofit2 Authorization - Global Interceptor for access token
本文介绍了Retrofit2授权-访问令牌的全局拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Retrofit2
,
我想像这样将Token
添加到我的Header
中:
I'm trying to use Retrofit2
,
I want to add Token
to my Header
Like this:
Authorization: Bearer Token
但是下面的code
无效:
public interface APIService {
@Headers({"Authorization", "Bearer "+ token})
@GET("api/Profiles/GetProfile?id={id}")
Call<UserProfile> getUser(@Path("id") String id);
}
我的服务器是asp.net webApi
.请帮我该怎么办?
My server is asp.net webApi
. Please help what should I do?
推荐答案
您有两种选择-您可以将其添加为调用的参数-
You have two choices -- you can add it as a parameter to your call --
@GET("api/Profiles/GetProfile?id={id}")
Call<UserProfile> getUser(@Path("id") String id, @Header("Authorization") String authHeader);
这可能有点烦人,因为您必须在每次通话时都传入"Bearer" + token
.如果您没有太多需要令牌的呼叫,则此方法很合适.
This can be a bit annoying because you will have to pass in the "Bearer" + token
on each call. This is suitable if you don't have very many calls that require the token.
如果要将标头添加到所有请求,则可以使用okhttp拦截器-
If you want to add the header to all requests, you can use an okhttp interceptor --
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + token)
.build();
return chain.proceed(newRequest);
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(/** your url **/)
.addConverterFactory(GsonConverterFactory.create())
.build();
这篇关于Retrofit2授权-访问令牌的全局拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文