目前我的客户端仅在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();
}
});
但是我想改变这种行为,并且能够手动调用或者每次调用自动调用它吗?有可能吗?
答案 0 :(得分:3)
如果认证是可预测的并且与代理无关,则解决方案是实现Interceptor而不是Authenticator。
OkHttpClient.Builder clientBuilder = ...;
clientBuilder.networkInterceptors().add(0, myInterceptor);
client = clientBuilder.build();
n.b。在https://github.com/square/okhttp/pull/2458中讨论了对此用例的可能支持。当前Authenticator API的一个问题是它假定来自失败的(401)请求的响应。