Apache HttpClient基本认证示例

x33g5p2x  于2022-10-07 转载在 Apache  
字(4.6k)|赞(0)|评价(0)|浏览(968)

本教程将演示如何在Apache HttpClient 4.5+上配置基本身份验证。
如果您想深入挖掘并学习HttpClient可以做的其他很酷的事情,请转到Apache HttpClient的主要教程。

使用HttpClient进行基本用户身份验证

这是一个简单的示例,使用HttpClient对需要用户身份验证的目标站点执行HTTP请求。在这个示例中,我们使用的是http://httpbin.org站点,它公开了几个示例Rest服务。
HttpClient提供了一个CredentialsProvider类,用于以标准方式配置基本身份验证:

  1. package com.javadevelopersguide.httpclient.siteexamples;
  2. import org.apache.http.auth.AuthScope;
  3. import org.apache.http.auth.UsernamePasswordCredentials;
  4. import org.apache.http.client.CredentialsProvider;
  5. import org.apache.http.client.methods.CloseableHttpResponse;
  6. import org.apache.http.client.methods.HttpGet;
  7. import org.apache.http.impl.client.BasicCredentialsProvider;
  8. import org.apache.http.impl.client.CloseableHttpClient;
  9. import org.apache.http.impl.client.HttpClients;
  10. import org.apache.http.util.EntityUtils;
  11. /**
  12. * A simple example that uses HttpClient to execute an HTTP request against
  13. * a target site that requires user authentication.
  14. * @author Ramesh Fadatare
  15. */
  16. public class ClientAuthentication {
  17. public static void main(String[] args) throws Exception {
  18. CredentialsProvider credsProvider = new BasicCredentialsProvider();
  19. credsProvider.setCredentials(
  20. new AuthScope("httpbin.org", 80),
  21. new UsernamePasswordCredentials("user", "passwd"));
  22. CloseableHttpClient httpclient = HttpClients.custom()
  23. .setDefaultCredentialsProvider(credsProvider)
  24. .build();
  25. try {
  26. HttpGet httpget = new HttpGet("http://httpbin.org/basic-auth/user/passwd");
  27. System.out.println("Executing request " + httpget.getRequestLine());
  28. CloseableHttpResponse response = httpclient.execute(httpget);
  29. try {
  30. System.out.println("----------------------------------------");
  31. System.out.println(response.getStatusLine());
  32. System.out.println(EntityUtils.toString(response.getEntity()));
  33. } finally {
  34. response.close();
  35. }
  36. } finally {
  37. httpclient.close();
  38. }
  39. }
  40. }

输出

  1. Executing request GET http://httpbin.org/basic-auth/user/passwd HTTP/1.1
  2. ----------------------------------------
  3. HTTP/1.1 200 OK
  4. {
  5. "authenticated": true,
  6. "user": "user"
  7. }

抢占式基本身份验证

开箱即用的HttpClient不进行抢占式身份验证–这必须由客户明确决定。
首先,我们需要创建HttpContext–使用预先选择了正确类型的身份验证方案的身份验证缓存对其进行预填充。

抢占式基本身份验证示例

可以自定义HttpClient的示例,以使用BASIC方案进行抢占式身份验证。通常,抢占式身份验证被认为不如对身份验证质询的响应安全,因此不鼓励这样做。

  1. package com.javadevelopersguide.httpclient.siteexamples;
  2. import org.apache.http.HttpHost;
  3. import org.apache.http.auth.AuthScope;
  4. import org.apache.http.auth.UsernamePasswordCredentials;
  5. import org.apache.http.client.AuthCache;
  6. import org.apache.http.client.CredentialsProvider;
  7. import org.apache.http.client.methods.CloseableHttpResponse;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.client.protocol.HttpClientContext;
  10. import org.apache.http.impl.auth.BasicScheme;
  11. import org.apache.http.impl.client.BasicAuthCache;
  12. import org.apache.http.impl.client.BasicCredentialsProvider;
  13. import org.apache.http.impl.client.CloseableHttpClient;
  14. import org.apache.http.impl.client.HttpClients;
  15. import org.apache.http.util.EntityUtils;
  16. /**
  17. * An example of HttpClient can be customized to authenticate
  18. * preemptively using BASIC scheme.
  19. * <b>
  20. * Generally, preemptive authentication can be considered less
  21. * secure than a response to an authentication challenge
  22. * and therefore discouraged.
  23. * @author Ramesh Fadatare
  24. */
  25. public class ClientPreemptiveBasicAuthentication {
  26. public static void main(String[] args) throws Exception {
  27. HttpHost target = new HttpHost("httpbin.org", 80, "http");
  28. CredentialsProvider credsProvider = new BasicCredentialsProvider();
  29. credsProvider.setCredentials(
  30. new AuthScope(target.getHostName(), target.getPort()),
  31. new UsernamePasswordCredentials("user", "passwd"));
  32. CloseableHttpClient httpclient = HttpClients.custom()
  33. .setDefaultCredentialsProvider(credsProvider).build();
  34. try {
  35. // Create AuthCache instance
  36. AuthCache authCache = new BasicAuthCache();
  37. // Generate BASIC scheme object and add it to the local
  38. // auth cache
  39. BasicScheme basicAuth = new BasicScheme();
  40. authCache.put(target, basicAuth);
  41. // Add AuthCache to the execution context
  42. HttpClientContext localContext = HttpClientContext.create();
  43. localContext.setAuthCache(authCache);
  44. HttpGet httpget = new HttpGet("http://httpbin.org/hidden-basic-auth/user/passwd");
  45. System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
  46. CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
  47. try {
  48. System.out.println("----------------------------------------");
  49. System.out.println(response.getStatusLine());
  50. System.out.println(EntityUtils.toString(response.getEntity()));
  51. } finally {
  52. response.close();
  53. }
  54. } finally {
  55. httpclient.close();
  56. }
  57. }
  58. }

输出

  1. Executing request GET http://httpbin.org/hidden-basic-auth/user/passwd HTTP/1.1 to target http://httpbin.org:80
  2. ----------------------------------------
  3. HTTP/1.1 200 OK
  4. {
  5. "authenticated": true,
  6. "user": "user"
  7. }

相关文章

最新文章

更多