使用 httpclient 4.x 验证单个请求
我有一个由多个线程共享的 HttpClient 实例。我想用它来发出单个经过身份验证的请求。因为只应验证单个请求,所以我不想按照 文档。这是我已经解决的问题,但不起作用。据我所知,CredentialsProvider
看起来根本没有被使用。有什么建议吗?
HttpContext context = null;
if(feedSpec.isAuthenticated()) {
context = new BasicHttpContext();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(feedSpec.getHttpUsername(), feedSpec.getHttpPassword()));
context.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
context.setAttribute(ClientPNames.HANDLE_AUTHENTICATION, true);
}
HttpGet httpGet = new HttpGet(feedSpec.getUri());
HttpResponse httpResponse = httpClient.execute(httpGet, context);
I have an HttpClient
instance that's shared by a number of threads. I would like to use it to make a single authenticated request. Because only the single request should be authenticated, I don't want to modify the HttpClient
instance as described in the documentation. Here's what I've worked out instead, which isn't working. From what I can tell, it doesn't look like the CredentialsProvider
is being used at all. Any tips?
HttpContext context = null;
if(feedSpec.isAuthenticated()) {
context = new BasicHttpContext();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(feedSpec.getHttpUsername(), feedSpec.getHttpPassword()));
context.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
context.setAttribute(ClientPNames.HANDLE_AUTHENTICATION, true);
}
HttpGet httpGet = new HttpGet(feedSpec.getUri());
HttpResponse httpResponse = httpClient.execute(httpGet, context);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实证明我连接的服务器只提供 NTLM 身份验证。我使用此处指南实现了 NTLM 身份验证。我修改了问题中列出的代码,使其看起来像这样并且有效:
It turns out the server I was connecting to was only offering NTLM authentication. I implemented NTLM authentication using the guide here. I modified the code listed in my question to look like so and it works: