gpt4 book ai didi

java - Apache HttpClient、基本身份验证和 session cookie

转载 作者:行者123 更新时间:2023-11-30 05:52:49 24 4
gpt4 key购买 nike

我想调用需要基本身份验证的 Web 服务。我无法使用抢占式身份验证,因为该服务返回带有特定 cookie 的代码 401。该 cookie 必须与基本身份验证 header 一起在响应中发送。以下代码不起作用:

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
Credentials credentials = new UsernamePasswordCredentials("user", "password");
credentialsProvider.setCredentials(AuthScope.ANY, credentials);

RequestConfig requestConfig = RequestConfig.custom()
.setCookieSpec(CookieSpecs.DEFAULT)
.build();

HttpClient httpClient = HttpClientBuilder.create()
.setDefaultCredentialsProvider(credentialsProvider)
.setDefaultRequestConfig(requestConfig)
.build();

HttpGet get = new HttpGet("https://a.something.com/something");
try {
HttpResponse response = httpClient.execute(get);
System.out.println(response.getStatusLine());
} catch (IOException e) {
e.printStackTrace();
}

在日志中,我可以看到 HttpClient 对代码 401 使用react,并且它正在使用基本身份验证数据第二次发送请求。但 cookie 丢失了:

http-outgoing-0 >> "GET /something HTTP/1.1[\r][\n]"
http-outgoing-0 >> "Host: a.something.com[\r][\n]"
http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_172)[\r][\n]"
http-outgoing-0 >> "[\r][\n]"
http-outgoing-0 << "HTTP/1.1 401 Unauthorized[\r][\n]"
http-outgoing-0 << "WWW-authenticate: basic realm="XXXXXX"[\r][\n]"
http-outgoing-0 << "Set-Cookie: SMCHALLENGE=YES; path=/; domain=.something.com; secure; HTTPOnly[\r][\n]"
http-outgoing-0 >> "GET /something HTTP/1.1[\r][\n]"
http-outgoing-0 >> "Host: a.something.com[\r][\n]"
http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_172)[\r][\n]"
http-outgoing-0 >> "Authorization: Basic xxxxxxxxxxxxxxx[\r][\n]"
http-outgoing-0 >> "[\r][\n]"
http-outgoing-0 << "HTTP/1.1 403 Forbidden[\r][\n]"

使用调试器,我直到出现以下行:https://github.com/apache/httpcomponents-client/blob/6f4550ff977a8f497822a17115572dcdb6e715b6/httpclient/src/main/java/org/apache/http/impl/execchain/MainClientExec.java#L272

在此循环中,请求第一次被执行。然后,在第 293 行,方法“needsAuthentication()”返回 true,请求再次执行。但我不明白应该将第一个响应中的 cookie 复制到第二个请求中。

最佳答案

在研究了 MainClientExec.java (见上文)后,我认为这要么是一个错误,要么根本不是受支持的功能:Apache HttpClient 不会在“401”重试中设置 cookie。

关于java - Apache HttpClient、基本身份验证和 session cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53630473/

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