Apache HttpClient基本认证示例

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

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

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

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

package com.javadevelopersguide.httpclient.siteexamples;

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.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
* A simple example that uses HttpClient to execute an HTTP request against
* a target site that requires user authentication.
* @author Ramesh Fadatare
*/
public class ClientAuthentication {

    public static void main(String[] args) throws Exception {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
            new AuthScope("httpbin.org", 80),
            new UsernamePasswordCredentials("user", "passwd"));
        CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider)
            .build();
        try {
            HttpGet httpget = new HttpGet("http://httpbin.org/basic-auth/user/passwd");

            System.out.println("Executing request " + httpget.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

输出

Executing request GET http://httpbin.org/basic-auth/user/passwd HTTP/1.1
----------------------------------------
HTTP/1.1 200 OK
{
  "authenticated": true, 
  "user": "user"
}

抢占式基本身份验证

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

抢占式基本身份验证示例

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

package com.javadevelopersguide.httpclient.siteexamples;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
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.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
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;

/**
* An example of HttpClient can be customized to authenticate
* preemptively using BASIC scheme.
* <b>
* Generally, preemptive authentication can be considered less
* secure than a response to an authentication challenge
* and therefore discouraged.
* @author Ramesh Fadatare
*/
public class ClientPreemptiveBasicAuthentication {

    public static void main(String[] args) throws Exception {
        HttpHost target = new HttpHost("httpbin.org", 80, "http");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
            new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("user", "passwd"));
        CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider).build();
        try {

            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();
            // Generate BASIC scheme object and add it to the local
            // auth cache
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(target, basicAuth);

            // Add AuthCache to the execution context
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            HttpGet httpget = new HttpGet("http://httpbin.org/hidden-basic-auth/user/passwd");

            System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

输出

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

相关文章

微信公众号

最新文章

更多