问题
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:
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);
来源:https://stackoverflow.com/questions/2516345/authenticating-a-single-request-with-httpclient-4-x