3

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?

toom
  • 12,864
  • 27
  • 89
  • 128

2 Answers2

10

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 );
Community
  • 1
  • 1
toom
  • 12,864
  • 27
  • 89
  • 128
  • can you tell me what `ac` is referring to when you call `ac.toXMLString()`? – Jason Crosby Mar 13 '14 at 17:13
  • `ac` is an object of a custom class I've written and the `toXMLString()` is a method that I implemented myself (like `toString()`). The results is an xml string for an http API. Since this is the POST's request payload this can be any arbitrary text and is not directly related to the question. – toom Mar 15 '14 at 00:29
-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);
pajaja
  • 2,164
  • 4
  • 25
  • 33