首页 文章

HttpClient基本授权错误

提问于
浏览
0

我正在尝试使用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 回答

相关问题