gpt4 book ai didi

okhttp - 手动启用验证器

转载 作者:行者123 更新时间:2023-12-01 13:42:34 25 4
gpt4 key购买 nike

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

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

关于okhttp - 手动启用验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38738982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com