使用 httpclient 4.x 验证单个请求 [英] Authenticating a single request with httpclient 4.x

查看:30
本文介绍了使用 httpclient 4.x 验证单个请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由多个线程共享的 HttpClient 实例.我想用它来发出一个经过身份验证的请求.因为应该只对单个请求进行身份验证,所以我不想修改 HttpClient 实例,如 文档.这是我已经制定出来的,但行不通.据我所知,看起来根本没有使用 CredentialsProvider .有什么提示吗?

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);

推荐答案

原来我连接的服务器只提供 NTLM 身份验证.我使用here指南实现了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:

HttpContext context = null;
if(feedSpec.isAuthenticated()) {
    context = new BasicHttpContext();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(feedSpec.getHttpUsername(), feedSpec.getHttpPassword(), "", ""));
    context.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
}
HttpGet httpGet = new HttpGet(feedSpec.getUri());
HttpResponse httpResponse = httpClient.execute(httpGet, context);

这篇关于使用 httpclient 4.x 验证单个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆