apache httpclient不设置基本身份验证凭据

too*_*oom 3 java httpclient basic-authentication

看看下面的代码:

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 );
Run Code Online (Sandbox Code Playgroud)

它不会产生任何错误.但是来自服务器的响应我得到"No Authorization header".使用Wireshark检查请求表明确实没有基本的身份验证集.

怎么可能?

too*_*oom 9

好的,默认情况下,基本身份验证已关闭.但是,启用它太复杂了(链接).因此可以使用此代码,它可以正常工作:

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 );
Run Code Online (Sandbox Code Playgroud)