我们在Android应用程序中使用 retrofit ,与OAuth2安全服务器通信.一切都很好,我们使用RequestInterceptor在每次调用中包含访问令牌.

推荐答案

请不要使用Interceptors来处理身份验证.

目前,处理身份验证的最佳方法是使用专门为this purpose设计的新的AuthenticatorAPI.

当响应为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);

Android相关问答推荐

三星上的某些应用程序已禁用通知权限切换

修改参数应该应用于哪些子元素?

Jetpack编写Lazy列滑动删除动画不顺利结束

如何在初始合成期间在可组合函数中调用/获取远程API中的数据[防止无限重组]

从不可组合回调打开可组合屏幕

为什么第二个代码可以安全地在 map 中进行网络调用,因为它已被缓存?

同样的参数值下,为什么requiredSizeIn不等于requiredWidthIn + requiredHeightIn?

Jetpack Compose 中带有权重的行和 AnimatedVisibility 会 destruct UI

任务 ':app:checkReleaseDuplicateClasses' 执行失败

如何在 Jetpack Compose 中向图像视图添加对角色带?

未解决的参考:pagerTabIndicatorOffset

如何像 XML 一样在 Compose Android Studio 中折叠/展开小部件代码区域/区域

在 Jetpack Compose 中更改列中子项的对齐方式

将应用更改为暗模式后 Android MainActivity 数据泄漏

在alert 对话框生成器中启动协程

如何在包含 Jetpack Compose 内容的布局中使用权重

Jetpack compose 绘制形状

如何在 Android Studio 中使用 Github Copilot?

我可以在不解密的情况下使用 JSch 获取加密的 SSH 私钥的类型或 fingerprint 吗?

Jetpack Compose Tapjacking:过滤对模糊 UI 的touch