查看以下代码:
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检查请求表明确实没有基本的身份验证集。
这怎么可能?
答案 0 :(得分: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 :(得分:-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);