我们在Android应用程序中使用 retrofit ,与OAuth2安全服务器通信.一切都很好,我们使用RequestInterceptor在每次调用中包含访问令牌.
我们在Android应用程序中使用 retrofit ,与OAuth2安全服务器通信.一切都很好,我们使用RequestInterceptor在每次调用中包含访问令牌.
请不要使用Interceptors
来处理身份验证.
目前,处理身份验证的最佳方法是使用专门为this purpose设计的新的Authenticator
API.
当响应为401 Not Authorised
retrying last failed request时,OkHttp将为Authenticator
提供凭据.
public class TokenAuthenticator implements Authenticator {
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
// Refresh your access_token using a synchronous api request
newAccessToken = service.refreshToken();
// Add new header to rejected request and retry it
return response.request().newBuilder()
.header(AUTHORIZATION, newAccessToken)
.build();
}
@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
// Null indicates no attempt to authenticate.
return null;
}
将Authenticator
连接到OkHttpClient
,方法与Interceptors
相同
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setAuthenticator(authAuthenticator);
创建Retrofit
RestAdapter
时使用此客户端
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(ENDPOINT)
.setClient(new OkClient(okHttpClient))
.build();
return restAdapter.create(API.class);