手动启用验证器

Enable authenticator manually

目前我的客户端仅在 401 响应的情况下验证请求:

this.client.authenticator(new okhttp3.Authenticator() {

      public Request authenticate(Route route, Response response) throws IOException {
      String credentials = authenticator.getCredentials();
      if (credentials.equals(response.request().header("Authorization"))) {
            throw new TraversonException(401, "Unauthorized", response.request().url().toString());
      } else {
            defaultHeader("Authorization", credentials);

            Request.Builder newRequest = response.request().newBuilder()
                                .headers(Headers.of(defaultHeaders));

             return newRequest.build();
         }
});

但我想更改此行为并能够在第一次调用时手动或自动调用它?有可能吗?

如果可以预见需要身份验证并且与代理无关,那么解决方案是实现拦截器而不是身份验证器。

OkHttpClient.Builder clientBuilder = ...;
clientBuilder.networkInterceptors().add(0, myInterceptor);
client = clientBuilder.build();

拦截器示例 https://github.com/yschimke/oksocial/blob/48e0ca53b85e608443eab614829cb0361c79aa47/src/main/java/com/baulsupp/oksocial/uber/UberAuthInterceptor.java

n.b。在 https://github.com/square/okhttp/pull/2458 中讨论了对该用例的可能支持。当前 Authenticator API 的一个问题是它假定失败 (401) 请求的响应。