【发布时间】:2018-12-05 10:43:54
【问题描述】:
我想调用需要基本身份验证的 Web 服务。我不能使用抢先式身份验证,因为该服务返回带有特定 cookie 的代码 401。此 cookie 必须与基本身份验证标头一起在响应中发送。以下代码不起作用:
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 做出反应,并且它正在第二次发送带有基本身份验证数据的请求。但是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]"
在这个循环中,请求第一次被执行。然后,在第 293 行,“needsAuthentication()”方法返回 true,请求再次执行。但我没有看到,第一个响应中的 cookie 应该复制到第二个请求的哪里。
【问题讨论】:
标签: java apache-httpclient-4.x