httpclient实现digest认证
时间: 2023-09-05 14:13:20 浏览: 134
HttpClient可以通过提供的CredentialsProvider接口来实现digest认证。下面是一个示例代码:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class DigestAuthExample {
public static void main(String[] args) throws IOException {
String username = "user";
String password = "password";
HttpHost target = new HttpHost("localhost", 8080, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(target.getHostName(), target.getPort()),
new UsernamePasswordCredentials(username, password));
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
HttpClientContext context = HttpClientContext.create();
HttpGet httpGet = new HttpGet("/");
CloseableHttpResponse response = httpClient.execute(target, httpGet, context);
try {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
} finally {
response.close();
}
// Get the digest scheme from the context
DigestScheme digestScheme = (DigestScheme) context.getAuthScheme(target);
// Use the digest scheme to generate the next request's headers
HttpGet httpGet2 = new HttpGet("/");
httpGet2.addHeader(digestScheme.authenticate(
new UsernamePasswordCredentials(username, password),
httpGet2, context));
CloseableHttpResponse response2 = httpClient.execute(target, httpGet2, context);
try {
HttpEntity entity = response2.getEntity();
EntityUtils.consume(entity);
} finally {
response2.close();
}
}
}
```
这个示例代码中,使用了BasicCredentialsProvider来提供用户名和密码。当httpClient执行第一次请求时,服务器返回401 Unauthorized响应,httpClient会尝试使用提供的凭据进行认证。然后,httpClient会使用DigestScheme生成下一个请求的摘要认证头。在第二次请求中,httpClient使用这个头来进行认证。
阅读全文