替换回httpclient,将httpclient配置独立出来提供更多可配置项目

This commit is contained in:
ben
2016-02-23 18:12:49 +08:00
parent f45562d9b0
commit c61fcb26c6
18 changed files with 472 additions and 257 deletions

View File

@ -0,0 +1,51 @@
package me.chanjar.weixin.common.util.http;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
/**
* httpclient build interface
*/
public interface ApacheHttpClientBuilder {
/**
* 构建httpclient实例
* @return new instance of CloseableHttpClient
*/
CloseableHttpClient build();
/**
* 代理服务器地址
* @param httpProxyHost
* @return
*/
ApacheHttpClientBuilder httpProxyHost(String httpProxyHost);
/**
* 代理服务器端口
* @param httpProxyPort
* @return
*/
ApacheHttpClientBuilder httpProxyPort(int httpProxyPort);
/**
* 代理服务器用户名
* @param httpProxyUsername
* @return
*/
ApacheHttpClientBuilder httpProxyUsername(String httpProxyUsername);
/**
* 代理服务器密码
* @param httpProxyPassword
* @return
*/
ApacheHttpClientBuilder httpProxyPassword(String httpProxyPassword);
/**
* ssl连接socket工厂
* @param sslConnectionSocketFactory
* @return
*/
ApacheHttpClientBuilder sslConnectionSocketFactory(SSLConnectionSocketFactory sslConnectionSocketFactory);
}

View File

@ -0,0 +1,199 @@
package me.chanjar.weixin.common.util.http;
import me.chanjar.weixin.common.util.StringUtils;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* httpclient 连接管理器
*/
@NotThreadSafe
public class DefaultApacheHttpHttpClientBuilder implements ApacheHttpClientBuilder {
private int connectionRequestTimeout = 3000;
private int connectionTimeout = 5000;
private int soTimeout = 5000;
private int idleConnTimeout = 60000;
private int checkWaitTime = 5000;
private int maxConnPerHost = 10;
private int maxTotalConn = 50;
private String userAgent;
private HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
return false;
}
};
private SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
private PlainConnectionSocketFactory plainConnectionSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
private String httpProxyHost;
private int httpProxyPort;
private String httpProxyUsername;
private String httpProxyPassword;
/**
* 连接管理器
*/
private PoolingHttpClientConnectionManager connectionManager;
/**
* 闲置连接监控线程
*/
private IdleConnectionMonitorThread idleConnectionMonitorThread;
/**
* httpClientBuilder
*/
private HttpClientBuilder httpClientBuilder;
private boolean prepared = false;
private DefaultApacheHttpHttpClientBuilder() {
}
public static DefaultApacheHttpHttpClientBuilder get() {
return new DefaultApacheHttpHttpClientBuilder();
}
public ApacheHttpClientBuilder httpProxyHost(String httpProxyHost) {
this.httpProxyHost = httpProxyHost;
return this;
}
public ApacheHttpClientBuilder httpProxyPort(int httpProxyPort) {
this.httpProxyPort = httpProxyPort;
return this;
}
public ApacheHttpClientBuilder httpProxyUsername(String httpProxyUsername) {
this.httpProxyUsername = httpProxyUsername;
return this;
}
public ApacheHttpClientBuilder httpProxyPassword(String httpProxyPassword) {
this.httpProxyPassword = httpProxyPassword;
return this;
}
public ApacheHttpClientBuilder sslConnectionSocketFactory(SSLConnectionSocketFactory sslConnectionSocketFactory){
this.sslConnectionSocketFactory = sslConnectionSocketFactory;
return this;
}
public IdleConnectionMonitorThread getIdleConnectionMonitorThread() {
return idleConnectionMonitorThread;
}
private void prepare(){
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainConnectionSocketFactory)
.register("https", sslConnectionSocketFactory)
.build();
connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(maxTotalConn);
connectionManager.setDefaultMaxPerRoute(maxConnPerHost);
connectionManager.setDefaultSocketConfig(
SocketConfig.copy(SocketConfig.DEFAULT)
.setSoTimeout(soTimeout)
.build()
);
idleConnectionMonitorThread = new IdleConnectionMonitorThread(connectionManager, idleConnTimeout, checkWaitTime);
idleConnectionMonitorThread.setDaemon(true);
idleConnectionMonitorThread.start();
httpClientBuilder = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(
RequestConfig.custom()
.setSocketTimeout(soTimeout)
.setConnectTimeout(connectionTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.build()
)
.setRetryHandler(httpRequestRetryHandler);
if (StringUtils.isNotBlank(httpProxyHost) && StringUtils.isNotBlank(httpProxyUsername)) {
// 使用代理服务器 需要用户认证的代理服务器
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(httpProxyHost, httpProxyPort),
new UsernamePasswordCredentials(httpProxyUsername, httpProxyPassword));
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
}
if (StringUtils.isNotBlank(userAgent)) {
httpClientBuilder.setUserAgent(userAgent);
}
}
public CloseableHttpClient build() {
if(!prepared){
prepare();
prepared = true;
}
return httpClientBuilder.build();
}
public static class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private final int idleConnTimeout;
private final int checkWaitTime;
private volatile boolean shutdown;
public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr, int idleConnTimeout, int checkWaitTime) {
super("IdleConnectionMonitorThread");
this.connMgr = connMgr;
this.idleConnTimeout = idleConnTimeout;
this.checkWaitTime = checkWaitTime;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(checkWaitTime);
connMgr.closeExpiredConnections();
connMgr.closeIdleConnections(idleConnTimeout, TimeUnit.MILLISECONDS);
}
}
} catch (InterruptedException ignore) {
}
}
public void trigger() {
synchronized (this) {
notifyAll();
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
}

View File

@ -74,6 +74,8 @@ public class MediaDownloadRequestExecutor implements RequestExecutor<File, Strin
File localFile = FileUtils.createTmpFile(inputStream, name_ext[0], name_ext[1], tmpDirFile);
return localFile;
}finally {
httpGet.releaseConnection();
}
}

View File

@ -1,9 +1,8 @@
package me.chanjar.weixin.common.util.http;
import java.io.File;
import java.io.IOException;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
@ -13,11 +12,11 @@ import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.File;
import java.io.IOException;
/**
* 上传媒体文件请求执行器请求的参数是File, 返回的结果是String
* @author Daniel Qian
@ -48,6 +47,8 @@ public class MediaUploadRequestExecutor implements RequestExecutor<WxMediaUpload
throw new WxErrorException(error);
}
return WxMediaUploadResult.fromJson(responseContent);
}finally {
httpPost.releaseConnection();
}
}

View File

@ -1,17 +1,16 @@
package me.chanjar.weixin.common.util.http;
import java.io.IOException;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.IOException;
/**
* 简单的GET请求执行器请求的参数是String, 返回的结果也是String
* @author Daniel Qian
@ -40,6 +39,8 @@ public class SimpleGetRequestExecutor implements RequestExecutor<String, String>
throw new WxErrorException(error);
}
return responseContent;
}finally {
httpGet.releaseConnection();
}
}

View File

@ -1,24 +1,17 @@
package me.chanjar.weixin.common.util.http;
import java.io.IOException;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.http.Consts;
import org.apache.http.HttpHost;
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.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
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;
/**
* 简单的POST请求执行器请求的参数是String, 返回的结果也是String
@ -47,6 +40,8 @@ public class SimplePostRequestExecutor implements RequestExecutor<String, String
throw new WxErrorException(error);
}
return responseContent;
}finally {
httpPost.releaseConnection();
}
}