如何从 Okhttp Authenticator 发出 HTTP 请求?

How to make HTTP request from Okhttp Authenticator?

我正在使用 Okhttp3,我想构建一个 OAuth2 Authenticator

有时,我需要从 Authenticator 本身发出 http 请求(即:刷新令牌),但 api 没有提供执行此操作的方法。

当然,我可以创建一个新的 okhttp 实例,但我不知道这是否是推荐的做法。

这是满足我需要的最佳做法吗?

开箱即用是不可能的,但可以使用一些解决方法:

  • Authenticator 中创建 OkHttpClient 的新实例,或者
  • 在 Authenticator 中添加一个 setHttpClient 方法

.

MyAuthenticator authenticator = new MyAuthenticator();
OkHttpClient client = new OkHttpClient.Builder()
    .authenticator(authenticator)
    .build();
authenticator.setHttpClient(client);

发件人:https://github.com/square/okhttp/issues/2733