使用httpclient发送digestAuth认证的请求
以下是使用httpclient发送digestAuth认证的请求的示例代码:
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.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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class DigestAuthExample {
public static void main(String[] args) throws Exception {
String username = "username";
String password = "password";
String url = "http://example.com/api/resource";
HttpHost targetHost = new HttpHost("example.com", 80, "http");
CloseableHttpClient httpClient = HttpClients.createDefault();
// Create authentication context
DigestScheme digestAuth = new DigestScheme();
digestAuth.overrideParamter("realm", "example.com");
digestAuth.overrideParamter("nonce", "1234567890");
digestAuth.overrideParamter("qop", "auth");
digestAuth.overrideParamter("algorithm", "MD5");
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(authScope, new BasicCredentialsProvider());
context.setAuthSchemeRegistry(AuthSchemeRegistryBuilder.create().register(AuthSchemes.DIGEST, digestAuth).build());
// Make the request
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(targetHost, httpGet, context);
// Get the response body
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
// Print the response body
System.out.println(responseBody);
// Close the response and the client
response.close();
httpClient.close();
}
}
在此示例中,我们首先定义了目标主机(targetHost)和要发送的HTTP请求的URL(url)。然后,我们使用HttpClients.createDefault()方法创建一个HTTP客户端。接下来,我们创建了一个DigestScheme对象,并使用overrideParamter方法设置了必要的参数。然后,我们创建了一个AuthScope对象和一个UsernamePasswordCredentials对象,用于指定要使用的用户名和密码。接下来,我们创建了一个HttpClientContext对象,并使用setCredentialsProvider和setAuthSchemeRegistry方法将上面创建的AuthScope对象、UsernamePasswordCredentials对象和DigestScheme对象添加到上下文中。最后,我们使用httpClient.execute方法发送HTTP请求,并使用EntityUtils.toString方法从响应实体中获取响应正文。最后,我们打印响应正文并关闭响应和HTTP客户端
原文地址: https://www.cveoy.top/t/topic/hel2 著作权归作者所有。请勿转载和采集!