ApacheHttpClient中的基本身份验证模型似乎已损坏。库试图绕过身份验证并在没有
Authorization
头,当然失败了。然后库尝试重新发送请求,当然失败了,因为
InputStream
不能倒带。
BasicCredentialsProvider
使用
HttpRequestInterceptor
设置标题:
HttpClientBuilder builder = HttpClientBuilder.create();
if (StringUtils.isNotBlank(username)) {
builder.addInterceptorFirst(new HttpRequestInterceptor()
{
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException
{
String token = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
request.addHeader("Authorization", "Basic "+token);
}
});
}