gpt4 book ai didi

具有基本身份验证的 Android OkHttp

转载 作者:IT老高 更新时间:2023-10-28 13:23:36 24 4
gpt4 key购买 nike

我正在为一个新项目使用 OkHttp 库,它的易用性给我留下了深刻的印象。我现在需要使用基本身份验证。不幸的是,缺乏工作示例代码。我正在寻找一个在遇到 HTTP 401 header 时如何将用户名/密码凭据传递给 OkAuthenticator 的示例。我查看了这个答案:

Retrofit POST request w/ Basic HTTP Authentication: "Cannot retry streamed HTTP body"

但这并没有让我走得太远。 OkHttp github repo 上的样本也没有基于身份验证的示例。有没有人有要点或其他代码示例让我指出正确的方向?感谢您的帮助!

最佳答案

okhttp3 的更新代码:

import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;

public class NetworkUtil {

private final OkHttpClient.Builder client;

{
client = new OkHttpClient.Builder();
client.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
if (responseCount(response) >= 3) {
return null; // If we've failed 3 times, give up. - in real life, never give up!!
}
String credential = Credentials.basic("name", "password");
return response.request().newBuilder().header("Authorization", credential).build();
}
});
client.connectTimeout(10, TimeUnit.SECONDS);
client.writeTimeout(10, TimeUnit.SECONDS);
client.readTimeout(30, TimeUnit.SECONDS);
}

private int responseCount(Response response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result++;
}
return result;
}

}

关于具有基本身份验证的 Android OkHttp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22490057/

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