看一下下面的代码:
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 );
它不会产生任何错误。然而,来自服务器的响应我得到“无授权标头”。使用 Wireshark 检查请求发现确实没有基本身份验证集。
这怎么可能?
好的,默认情况下基本身份验证是关闭的。然而,启用它太复杂了(link https://stackoverflow.com/questions/2014700/preemptive-basic-authentication-with-apache-httpclient-4)。因此,可以使用这段代码,它工作得很好:
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 );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)