使用httpclient 4.x验证单个请求

时间:2010-03-25 14:33:30

标签: java authentication apache-httpclient-4.x

我有一个HttpClient实例,由多个线程共享。我想用它来做一个经过身份验证的请求。由于只应对单个请求进行身份验证,因此我不想按documentation中所述修改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);

1 个答案:

答案 0 :(得分:3)

事实证明我连接的服务器只提供NTLM身份验证。我使用指南here实现了NTLM身份验证。我修改了我的问题中列出的代码,看起来是这样的,它可以工作:

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