apache httpclient doesn't set basic authentication credentials

这一生的挚爱 提交于 2019-12-23 18:29:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!