手动启用身份验证器

时间:2016-08-03 08:59:28

标签: okhttp okhttp3

目前我的客户端仅在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();
         }
});

但是我想改变这种行为,并且能够手动调用或者每次调用自动调用它吗?有可能吗?

1 个答案:

答案 0 :(得分:3)

如果认证是可预测的并且与代理无关,则解决方案是实现Interceptor而不是Authenticator。

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)请求的响应。