问题
Have a look at the following code:
DefaultHttpClient http = new DefaultHttpClient();
http.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(
Configuration.username,
Configuration.developerKey ) );
HttpPost post = new HttpPost(strURL);
StringEntity entity = new StringEntity( ac.toXMLString() );
entity.setContentType("text/xml");
post.setEntity( entity );
org.apache.http.HttpResponse response = http.execute( post );
It produces no errors. However a response from the server I get "No Authorization header". Checking the request with Wireshark unveils that there is indeed no basic authentication set.
How is that possible?
回答1:
Okay, by default the basic authentication is turned off. However, enabling it is far too complicated (link) . Therefore one can use this code, which works fine:
DefaultHttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost(strURL);
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(
Configuration.username,
Configuration.developerKey);
post.addHeader( BasicScheme.authenticate(creds,"US-ASCII",false) );
StringEntity entity = new StringEntity( ac.toXMLString() );
entity.setContentType("text/xml");
post.setEntity( entity );
org.apache.http.HttpResponse response = http.execute( post );
回答2:
User of credential provider
HttpClient client = new DefaultHttpClient();
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(apiUser,apiPassword);
provider.setCredentials(new AuthScope(apiHost, apiPort, AuthScope.ANY_REALM), credentials);
HttpComponentsClientHttpRequestFactory commons = new HttpComponentsClientHttpRequestFactory(client);
来源:https://stackoverflow.com/questions/18108783/apache-httpclient-doesnt-set-basic-authentication-credentials