猿问

使用翻新功能刷新OAuth令牌,而无需修改所有调用

我们正在Android应用中使用Retrofit,以与OAuth2安全服务器进行通信。一切正常,我们使用RequestInterceptor在每个调用中都包含访问令牌。但是,有时访问令牌将过期,并且令牌需要刷新。当令牌过期时,下一个调用将返回未经授权的HTTP代码,因此易于监控。我们可以通过以下方式修改每个Retrofit调用:在失败回调中,检查错误代码,如果错误代码等于Unauthorized,则刷新OAuth令牌,然后重复Retrofit调用。但是,为此,应修改所有调用,这不是一个易于维护的好的解决方案。有没有一种方法可以在不修改所有Retrofit调用的情况下进行此操作?



萧十郎
浏览 593回答 3
3回答

繁花如伊

如果您使用的是Retrofit > =,1.9.0则可以使用OkHttp的新Interceptor(已在中引入)OkHttp 2.2.0。您可能需要使用Application Interceptor,它允许您进行以下操作retry and make multiple calls。您的拦截器可能类似于以下伪代码:public class CustomInterceptor implements Interceptor {    @Override    public Response intercept(Chain chain) throws IOException {        Request request = chain.request();        // try the request        Response response = chain.proceed(request);        if (response shows expired token) {            // get a new token (I use a synchronous Retrofit call)            // create a new request and modify it accordingly using the new token            Request newRequest = request.newBuilder()...build();            // retry the request            return chain.proceed(newRequest);        }        // otherwise just pass the original response on        return response;    }}定义完后Interceptor,创建一个OkHttpClient并将拦截器添加为应用程序拦截器。    OkHttpClient okHttpClient = new OkHttpClient();    okHttpClient.interceptors().add(new CustomInterceptor());最后,OkHttpClient在创建时使用它RestAdapter。    RestService restService = new RestAdapter().Builder            ...            .setClient(new OkClient(okHttpClient))            .create(RestService.class);警告:由于Jesse Wilson(从广场)提到这里,这是权力的危险量。话虽如此,我绝对认为这是现在处理此类问题的最佳方法。如果您有任何疑问,请随时在评论中提问。
随时随地看视频慕课网APP

相关分类

Android
我要回答