toom
toom

Reputation: 13316

apache httpclient doesn't set basic authentication credentials

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?

Upvotes: 3

Views: 12155

Answers (2)

Howard Roark
Howard Roark

Reputation: 1

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

Upvotes: -1

toom
toom

Reputation: 13316

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

Upvotes: 10

Related Questions