ecology_maven/aiyh/utils/httpUtil/HttpManager.java

88 lines
3.3 KiB
Java
Raw Normal View History

2021-11-14 15:29:16 +08:00
package aiyh.utils.httpUtil;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
/**
* @author EBU7-dev1-ayh
* @since 2021/08/30 17:56
**/
public class HttpManager {
/**
*
*/
private static final int CONNECT_TIMEOUT = 30000;
private static final int CONNECTION_REQUEST_TIMEOUT = 10000;
private static final int SOCKET_TIMEOUT = 30000;
private static final int MAX_TOTAL = 500;
private static final int MAX_PRE_ROUTE = 500;
/**
*
*/
static RequestConfig requestConfig = RequestConfig.custom()
//网络请求的超时时间
.setConnectTimeout(CONNECT_TIMEOUT)
//连接池去获取连接的超时时间
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
//设置socket超时时间
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
static PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
static {
// 配置最大的连接数
manager.setMaxTotal(MAX_TOTAL);
// 每个路由最大连接数路由是根据host来管理的大小不好控制
manager.setDefaultMaxPerRoute(MAX_PRE_ROUTE);
}
/**
* urlhttp / https
* @param url
* @return
*/
public static CloseableHttpClient getHttpConnection(String url){
if(url.trim().toUpperCase().startsWith(HttpArgsType.HTTP_HTTPS.toUpperCase())){
SSLContext sslContext;
SSLConnectionSocketFactory sslsf = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> {
// 绕过所有验证
return true;
}).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
sslsf = new SSLConnectionSocketFactory(sslContext,hostnameVerifier);
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
e.printStackTrace();
}
return HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(manager)
.setConnectionManagerShared(true)
.setDefaultRequestConfig(requestConfig)
.build();
}else{
return HttpClients.custom()
.setConnectionManager(manager)
.setDefaultRequestConfig(requestConfig)
.setConnectionManagerShared(true)
.build();
}
}
}