我正在尝试使用4.3.6版本的org.apache.http.client.HttpClient执行REST API get请求,但收到401错误 . 我正在使用基本身份验证
这是我的示例代码
BasicCredentialsProvider credprov = new BasicCredentialsProvider();
credprov.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(API_USERNAME, API_PASSWORD));
HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCredentialsProvider(credprov);
HttpClient client = builder.build();
HttpGet httpget = new HttpGet(API_TEST_URI);
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
if (entity != null) {
entity.consumeContent();
}
httpClient.getConnectionManager().shutdown();
这是返回401,即使所有细节都是正确的 . 我正在通过HttpClient代码进行调试,发现原始响应返回401,WWW-Authenticate标头只是设置为“Basic”而没有别的 . 然后以MalformedChallengeException“Authentication challenge is empty”异常结束 .
我尝试过更改代码,直接使用基本身份验证在httpget变量上设置标头
httpget.addHeader("Authorization", "Basic " + Base64Encoder.encode ("username:password"));
这有效(表明身份验证详细信息是正确的 .
任何人都可以发现这种方法有任何问题,为什么它不起作用?
1 回答
您似乎已添加了提供的凭据,但尚未添加AuthCache,这是预先进行身份验证所必需的 .
HttpClient示例页面上列出了example of preemptive basic authentication:http://hc.apache.org/httpcomponents-client-ga/examples.html