看看下面的代码:
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 );
它不会产生任何错误。但是服务器的响应我得到“无授权 header ”。使用 Wireshark 检查请求会发现确实没有基本身份验证集。
这怎么可能?
最佳答案
好的,默认情况下基本身份验证是关闭的。但是,启用它太复杂了 (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 );
关于java - apache httpclient 不设置基本身份验证凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18108783/