Skip to content
This repository has been archived by the owner on Aug 20, 2021. It is now read-only.

Commit

Permalink
添加 CredentialsProviderBuilder fix #17
Browse files Browse the repository at this point in the history
HeadersPacker 重命名成 HttpRequestHeadersPacker  fix #16

feilong-net-httpclient4 要支持 basic author 认证  fix #15
  • Loading branch information
venusdrogon committed Mar 21, 2018
1 parent ff4ab6f commit 93fc97f
Show file tree
Hide file tree
Showing 8 changed files with 249 additions and 121 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Copyright (C) 2008 feilong
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.feilong.net.httpclient4.builder;

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.impl.client.BasicCredentialsProvider;

/**
* The Class CredentialsProviderBuilder.
*
* @author <a href="http://feitianbenyue.iteye.com/">feilong</a>
* @since 1.11.0
*/
public class CredentialsProviderBuilder{

/**
* Builds the credentials provider.
*
* @param targetHost
* the target host
* @param userName
* the user name
* @param password
* the password
* @return the credentials provider
*/
public static CredentialsProvider build(HttpHost targetHost,String userName,String password){
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
return build(authScope, userName, password);
}

//---------------------------------------------------------------

/**
* Builds the.
*
* @param authScope
* the auth scope
* @param userName
* the user name
* @param password
* the password
* @return the credentials provider
*/
public static CredentialsProvider build(AuthScope authScope,String userName,String password){
return build(authScope, new UsernamePasswordCredentials(userName, password));
}

/**
* Builds the.
*
* @param authScope
* the auth scope
* @param credentials
* the credentials
* @return the credentials provider
*/
public static CredentialsProvider build(AuthScope authScope,UsernamePasswordCredentials credentials){
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(authScope, credentials);
return credentialsProvider;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,18 @@
package com.feilong.net.httpclient4.builder;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.feilong.net.entity.ConnectionConfig;

/**
* HttpClient 构造器.
*
* @author <a href="http://feitianbenyue.iteye.com/">feilong</a>
*
* @see org.apache.http.impl.client.HttpClients#createDefault()
* @see org.apache.http.impl.client.HttpClients#custom()
* @see org.apache.http.impl.client.HttpClientBuilder#create()
* @since 1.10.6
*/
class HttpClientBuilder{
Expand All @@ -41,14 +46,14 @@ private HttpClientBuilder(){
*
* @return the closeable http client
*/
static HttpClient build(){
//TODO 处理 https
CloseableHttpClient createDefault = HttpClients.createDefault();
//TODO 处理 https
static HttpClient build(ConnectionConfig connectionConfig){
HttpClient httpClient = HttpClients.custom()//
//.setDefaultCredentialsProvider(CredentialsProviderBuilder.build(AuthScope.ANY, userName, password))//
.build();

// org.apache.http.impl.client.HttpClientBuilder customHttpClientBuilder = HttpClients.custom();
// customHttpClientBuilder.setSSLContext(sslContext);
// customHttpClientBuilder.setConnectionManager(connManager);
// CloseableHttpClient httpClient = customHttpClientBuilder.build();
return createDefault;
//customHttpClientBuilder.setSSLContext(sslContext);
//customHttpClientBuilder.setConnectionManager(connManager);
return httpClient;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ final class HttpHeaderListBuilder{
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(HttpHeaderListBuilder.class);

//---------------------------------------------------------------

/** Don't let anyone instantiate this class. */
private HttpHeaderListBuilder(){
//AssertionError不是必须的. 但它可以避免不小心在类的内部调用构造器. 保证该类在任何情况下都不会被实例化.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public static HttpResponse execute(HttpRequest httpRequest,ConnectionConfig conn

//---------------------------------------------------------------
try{
return HttpRequestExecuter.execute(httpUriRequest);
return HttpRequestExecuter.execute(httpUriRequest, connectionConfig);
}catch (SocketTimeoutException e){
String pattern = "{},httpRequest:[{}],useConnectionConfig:[{}]";
String message = Slf4jUtil.format(pattern, e.getMessage(), JsonUtil.format(httpRequest), JsonUtil.format(connectionConfig));
Expand All @@ -88,8 +88,9 @@ public static HttpResponse execute(HttpRequest httpRequest,ConnectionConfig conn
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private static HttpResponse execute(HttpUriRequest httpUriRequest) throws ClientProtocolException,IOException{
HttpClient httpClient = HttpClientBuilder.build();
private static HttpResponse execute(HttpUriRequest httpUriRequest,ConnectionConfig connectionConfig)
throws ClientProtocolException,IOException{
HttpClient httpClient = HttpClientBuilder.build(connectionConfig);
return httpClient.execute(httpUriRequest);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import com.feilong.net.entity.ConnectionConfig;
import com.feilong.net.entity.HttpRequest;
import com.feilong.net.httpclient4.builder.httpurirequest.HttpUriRequestFactory;
import com.feilong.net.httpclient4.packer.HeadersPacker;
import com.feilong.net.httpclient4.packer.HttpRequestHeadersPacker;

/**
* 专门用来构造 {@link HttpUriRequest}.
Expand Down Expand Up @@ -69,11 +69,9 @@ public static HttpUriRequest build(HttpRequest httpRequest,ConnectionConfig conn
}

//---------------------------------------------------------------

HttpUriRequest httpUriRequest = HttpUriRequestFactory.buildHttpUriRequest(httpRequest, connectionConfig);

HeadersPacker.setDefaultHeader(httpUriRequest);
HeadersPacker.setHeaders(httpUriRequest, httpRequest.getHeaderMap());
HttpRequestHeadersPacker.setHeaders(httpUriRequest, httpRequest.getHeaderMap(), connectionConfig);

return httpUriRequest;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,32 @@
*/
package com.feilong.net.httpclient4.packer;

import static com.feilong.core.Validator.isNotNullOrEmpty;
import static com.feilong.core.Validator.isNullOrEmpty;

import java.nio.charset.Charset;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpUriRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.feilong.net.entity.ConnectionConfig;
import com.feilong.net.entity.HttpRequest;

/**
* 专门用来封装请求头 {@link org.apache.http.HttpMessage#setHeader(String, String)}.
*
* @author <a href="http://feitianbenyue.iteye.com/">feilong</a>
* @since 1.10.6
* @since 1.11.0 rename from HeadersPacker
*/
public final class HeadersPacker{
public final class HttpRequestHeadersPacker{

/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(HeadersPacker.class);
private static final Logger LOGGER = LoggerFactory.getLogger(HttpRequestHeadersPacker.class);

//---------------------------------------------------------------

Expand All @@ -46,8 +51,31 @@ public final class HeadersPacker{
* the http uri request
* @param headerMap
* 请求header map, 如果 <code>headerMap</code> 是null或者empty,什么都不做<br>
* @param connectionConfig
* the connection config
*/
public static void setHeaders(HttpUriRequest httpUriRequest,Map<String, String> headerMap){
public static void setHeaders(HttpUriRequest httpUriRequest,Map<String, String> headerMap,ConnectionConfig connectionConfig){
setDefaultHeader(httpUriRequest);

setBasicAuthenticationHeader(httpUriRequest, connectionConfig);

//---------------------------------------------------------------

setHeaderMap(httpUriRequest, headerMap);
}

//---------------------------------------------------------------

/**
* 设置 header map.
*
* @param httpUriRequest
* the http uri request
* @param headerMap
* the header map
* @since 1.11.0
*/
private static void setHeaderMap(HttpUriRequest httpUriRequest,Map<String, String> headerMap){
if (isNullOrEmpty(headerMap)){
LOGGER.trace("input [headerMap] is null or empty ,skip!");
return;
Expand All @@ -65,12 +93,39 @@ public static void setHeaders(HttpUriRequest httpUriRequest,Map<String, String>
}
}

//---------------------------------------------------------------

/**
* 设置 basic authentication header.
*
* @param httpUriRequest
* the http uri request
* @param connectionConfig
* the connection config
* @since 1.11.0
*/
private static void setBasicAuthenticationHeader(HttpUriRequest httpUriRequest,ConnectionConfig connectionConfig){
String userName = connectionConfig.getUserName();
String password = connectionConfig.getPassword();

if (isNotNullOrEmpty(userName) && isNotNullOrEmpty(password)){

String auth = userName + ":" + password;
String authHeader = "Basic " + new String(Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII"))));

httpUriRequest.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
}
}

//---------------------------------------------------------------

/**
* 设置默认头.
*
*
* @param httpUriRequest
* the new default header
*/
public static void setDefaultHeader(HttpUriRequest httpUriRequest){
private static void setDefaultHeader(HttpUriRequest httpUriRequest){
httpUriRequest.setHeader(HttpHeaders.USER_AGENT, HttpRequest.DEFAULT_USER_AGENT);
//httpUriRequest.setHeader("Connection", "keep-alive");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* Copyright (C) 2008 feilong
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.http.auth;

import static com.feilong.core.CharsetType.UTF8;
import static com.feilong.core.util.CollectionsUtil.newArrayList;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.feilong.net.httpclient4.builder.CredentialsProviderBuilder;

public class CredentialsAdidasPtsTest{

private static final Logger LOGGER = LoggerFactory.getLogger(CredentialsAdidasPtsTest.class);

@Test
public void testCredentialsTest5() throws ClientProtocolException,IOException{
CloseableHttpClient httpclient = HttpClients.createDefault();

List<NameValuePair> nameValuePairList = newArrayList();
nameValuePairList.add(new BasicNameValuePair("j_username", "xin.jin"));
nameValuePairList.add(new BasicNameValuePair("j_password", "Aa123456"));

HttpPost httpPost = new HttpPost("/j_spring_security_check");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList));

HttpHost targetHost = new HttpHost("pts.adidas.com.cn", 443, "https");
HttpClientContext httpClientContext = buildHttpClientContext(targetHost);
CloseableHttpResponse closeableHttpResponse = httpclient.execute(targetHost, httpPost, httpClientContext);

LOGGER.debug(EntityUtils.toString(closeableHttpResponse.getEntity(), UTF8));
}

//---------------------------------------------------------------

private HttpClientContext buildHttpClientContext(HttpHost targetHost){
CredentialsProvider credentialsProvider = CredentialsProviderBuilder.build(targetHost, "adidas", "ad20170731");
// Lookup<AuthSchemeProvider> authRegistry = <...>
// // 创建 AuthCache 对象
AuthCache authCache = new BasicAuthCache();
// //创建 BasicScheme,并把它添加到 auth cache中
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);

// 把AutoCache添加到上下文中
HttpClientContext httpClientContext = HttpClientContext.create();
httpClientContext.setCredentialsProvider(credentialsProvider);
// context.setAuthSchemeRegistry(authRegistry);
// context.setAuthCache(authCache);

return httpClientContext;
}

}
Loading

0 comments on commit 93fc97f

Please sign in to comment.