我正在尝试使用 Retrofit2
,
我想将 Token
添加到我的 Header
像这样:
授权:承载 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
。请帮忙,我该怎么办?
最佳答案
你有两个选择——你可以将它作为参数添加到你的调用中——
@GET("api/Profiles/GetProfile?id={id}")
Call<UserProfile> getUser(@Path("id") String id, @Header("Authorization") String authHeader);
这可能有点烦人,因为您必须在每次调用时传入 "Bearer"+ token
。如果您没有太多需要 token 的调用,这很适合。
如果你想给所有请求添加header,可以使用okhttp拦截器——
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();
关于android - Retrofit2 Authorization - 访问 token 的全局拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41078866/