在进行DigestAuth认证时,可能会遇到无法正常工作的情况。可以采用以下代码示例来解决这个问题:
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClientBuilder.create().disableRedirectHandling().build();
HttpGet httpGet = new HttpGet(url);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(host, port),
new UsernamePasswordCredentials(username, password));
httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
String responseString = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在这个示例中,我们使用了HttpClientBuilder来创建HttpClient,并且禁用了重定向。然后,我们通过CredentialsProvider设置了必要的认证信息,包括AuthScope、用户名和密码等。最后,我们执行HttpGet请求,并获取响应实体并转换为字符串。在完成请求后,记得关闭httpClient。这样,我们就可以成功地使用DigestAuth进行认证。