HttpClient学习之三实现Basic认证

引用到的jar: httpclient-4.5.jar; httpcore-4.4.1.jar; commons-logging-1.2.jar; common-codec-1.9.jar

import java.io.IOException;

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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class HttpClientWithBasicAuth {
	
	private	HttpClientBuilder httpClientBuilder;
	private CloseableHttpClient closeableHttpClient;

	public String doGetMethod(String host, int port, String URI){
		if( closeableHttpClient == null ){
			//createCloseableHttpClient();
			createCloseableHttpClientWithBasicAuth();
		}
		String result = "";
		HttpGet httpGet = null;
		HttpResponse httpResponse = null;
		HttpEntity entity = null;
		httpGet = new HttpGet("http://"+host+URI);
		try {
			httpResponse = closeableHttpClient.execute(httpGet);
			entity = httpResponse.getEntity();
			if( entity != null ){
				result = EntityUtils.toString(entity);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
			
		return result;
	}
	
	
	public void closeHttpClient(){
		if( closeableHttpClient != null ){
			try {
				closeableHttpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void createCloseableHttpClient(){
		if( closeableHttpClient == null ){
			// 创建HttpClientBuilder
			httpClientBuilder = HttpClientBuilder.create();
			// HttpClient
			closeableHttpClient = httpClientBuilder.build();
		}
	}
	
	public void createCloseableHttpClientWithBasicAuth(){
		if( closeableHttpClient == null ){
			// 创建HttpClientBuilder
			httpClientBuilder = HttpClientBuilder.create();
			// 设置BasicAuth
			CredentialsProvider provider = new BasicCredentialsProvider();
		    // Create the authentication scope
		    AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
		    // Create credential pair,在此处填写用户名和密码
		    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("root", "superuser");
		    // Inject the credentials
		    provider.setCredentials(scope, credentials);
		    // Set the default credentials provider
		    httpClientBuilder.setDefaultCredentialsProvider(provider);
			// HttpClient
			closeableHttpClient = httpClientBuilder.build();
		}
	}
	
	/*private HttpClientContext createBasicAuthContext(HttpHost host,String username, String password) {
	    CredentialsProvider credsProvider = new BasicCredentialsProvider();
	    Credentials defaultCreds = new UsernamePasswordCredentials(username, password);
	    credsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), defaultCreds);

	    AuthCache authCache = new BasicAuthCache();
	    BasicScheme basicAuth = new BasicScheme();
	    authCache.put(host, basicAuth);

	    HttpClientContext context = HttpClientContext.create();
	    context.setCredentialsProvider(credsProvider);
	    context.setAuthCache(authCache);
	    return context;
	}*/

	public static void main(String args[])  {
		String host = "10.104.203.166";
		int port = 8080;
		String URI = "/redfish/v1/SessionService/Sessions";
		
		HttpClientWithBasicAuth httpClient = new HttpClientWithBasicAuth();
		String result = httpClient.doGetMethod(host, port, URI);
		System.out.println(result);
	}
}


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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使用这个头来进行认证

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值