views:

365

answers:

2

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);
+1  A: 

I do it in this way with commons-httpclient-2.0.2:

HttpClient client = new HttpClient();
PostMethod pm = new PostMethod("http://...");
pm.addRequestHeader("AUTHORIZATION", "Basic bXl1c2VyOm15cGFzcw==");
int code = client.executeMethod(pm);

The user and password are Base64 encoded. I used myuser:mypass

rodrigoap
httpclient 2.0.2 is 5.5 years old. Hopefully there's a more modern solution.
scompt.com
hey, my car is 15 years old and it works very well, even better than new ones.
rodrigoap
True, but the question specifies httpclient 4.x. None of those classes exist in that form in the newer versions.
scompt.com
A: 

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);
scompt.com
The URL of the guide linked in this comment changed, and is now: http://hc.apache.org/httpcomponents-client-ga/ntlm.html
Alessandro Vernet
I've updated my answer.
scompt.com