首页 文章

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

提问于
浏览
3

看看下面的代码:

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

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

怎么可能?

2 回答

  • 9

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

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

    凭证提供者的用户

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

相关问题