java httpclient digest
时间: 2023-11-29 11:46:16 浏览: 216
以下是使用Java HttpClient进行Digest认证的示例代码:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
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 HttpClientDigestAuthExample {
public static void main(String[] args) throws ClientProtocolException, IOException {
// 创建HttpClient实例
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建HttpGet请求
HttpGet httpget = new HttpGet("http://www.example.com/");
// 创建凭据提供程序
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("www.example.com", 80),
new UsernamePasswordCredentials("username", "password"));
// 设置凭据提供程序
httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
// 执行请求
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
// 打印响应内容
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
// 关闭连接
httpclient.close();
}
}
}
```
阅读全文