http连接池
package com.ruoyi.syndata.utils;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
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.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
/**
* HttpClient工具类
*
* @return
* @author sxsheng0103
* @create 2021年06月18日
*/
public class HttpClientUtil {
static final int timeOut = 10 * 1000;
private static CloseableHttpClient httpClient = null;
private final static Object syncLock = new Object();
private static void config(HttpRequestBase httpRequestBase) {
// 设置Header等
// httpRequestBase.setHeader("User-Agent", "Mozilla/5.0");
// httpRequestBase
// .setHeader("Accept",
// "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
// httpRequestBase.setHeader("Accept-Language",
// "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");// "en-US,en;q=0.5");
// httpRequestBase.setHeader("Accept-Charset",
// "ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7");
// 配置请求的超时设置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(timeOut)
.setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
httpRequestBase.setConfig(requestConfig);
}
/**
* 获取HttpClient对象
*
* @return
* @author SHANHY
* @create 2015年12月18日
*/
public static CloseableHttpClient getHttpClient(String url) {
String hostname = url.split("/")[2];
int port = 80;
if (hostname.contains(":")) {
String[] arr = hostname.split(":");
hostname = arr[0];
port = Integer.parseInt(arr[1]);
}
if (httpClient == null) {
synchronized (syncLock) {
if (httpClient == null) {
httpClient = createHttpClient(200, 40, 100, hostname, port);
try {//信任https
TrustManager[] tm = { new TrustManager() };
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, tm, null);
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
org.apache.http.conn.ssl.SSLSocketFactory sf = new org.apache.http.conn.ssl.SSLSocketFactory(sc, org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
// org.apache.http.conn.ssl.SSLSocketFactory sf = new org.apache.http.conn.ssl.SSLSocketFactory(trustStore);
sf.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
// httpClient = new DefaultHttpClient(ccm, httpClient.getParams());
httpClient = new DefaultHttpClient(ccm, params);;
}
}
}
}
return httpClient;
}
/**
* 创建HttpClient对象
*
* @return
* @author SHANHY
* @create 2015年12月18日
*/
public static CloseableHttpClient createHttpClient(int maxTotal,
int maxPerRoute, int maxRoute, String hostname, int port) {
ConnectionSocketFactory plainsf = PlainConnectionSocketFactory
.getSocketFactory();
LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory
.getSocketFactory();
Registry<ConnectionSocketFactory> registry = RegistryBuilder
.<ConnectionSocketFactory>create().register("http", plainsf)
.register("https", sslsf).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
registry);
// 将最大连接数增加
cm.setMaxTotal(maxTotal);
// 将每个路由基础的连接增加
cm.setDefaultMaxPerRoute(maxPerRoute);
HttpHost httpHost = new HttpHost(hostname, port);
// 将目标主机的最大连接数增加
cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
// 请求重试处理
HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception,
int executionCount, HttpContext context) {
if (executionCount >= 5) {// 如果已经重试了5次,就放弃
return false;
}
if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
return true;
}
if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
return false;
}
if (exception instanceof InterruptedIOException) {// 超时
return false;
}
if (exception instanceof UnknownHostException) {// 目标服务器不可达
return false;
}
if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
return false;
}
if (exception instanceof SSLException) {// SSL握手异常
return false;
}
HttpClientContext clientContext = HttpClientContext
.adapt(context);
HttpRequest request = clientContext.getRequest();
// 如果请求是幂等的,就再次尝试
if (!(request instanceof HttpEntityEnclosingRequest)) {
return true;
}
return false;
}
};
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.setRetryHandler(httpRequestRetryHandler).build();
return httpClient;
}
private static void setPostParams(HttpPost httpost,
Map<String, Object> params) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
}
try {
httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* GET请求URL获取内容
*
* @param url
* @return
* @throws IOException
* @author SHANHY
* @create 2015年12月18日
*/
public static String post(String url, Map<String, Object> params) throws IOException {
HttpPost httppost = new HttpPost(url);
config(httppost);
setPostParams(httppost, params);
CloseableHttpResponse response = null;
try {
response = getHttpClient(url).execute(httppost,
HttpClientContext.create());
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
return result;
} catch (Exception e) {
// e.printStackTrace();
throw e;
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* GET请求URL获取内容
*
* @param url
* @return
* @author SHANHY
* @create 2015年12月18日
*/
public static String get(String url) {
HttpGet httpget = new HttpGet(url);
config(httpget);
CloseableHttpResponse response = null;
try {
response = getHttpClient(url).execute(httpget,
HttpClientContext.create());
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity); //关闭HttpEntity是的流,如果手动关闭了InputStream instream = entity.getContent();这个流,也可以不调用这个方法
return result;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
String a = "{\"Authorization\": \"Bearer "+AuthHttpUtils.singleSecret()+"\"}";
// URL列表数组
String[] urisToGet = {
"http://blog.csdn.net/catoop/article/details/38849497",
"http://blog.csdn.net/catoop/article/details/38849497",
"http://blog.csdn.net/catoop/article/details/38849497",
"http://blog.csdn.net/catoop/article/details/38849497",
"http://blog.csdn.net/catoop/article/details/38849497",
"http://blog.csdn.net/catoop/article/details/38849497",
"http://blog.csdn.net/catoop/article/details/38849497"};
long start = System.currentTimeMillis();
try {
int pagecount = urisToGet.length;
ExecutorService executors = Executors.newFixedThreadPool(pagecount);
CountDownLatch countDownLatch = new CountDownLatch(pagecount);
for (int i = 0; i < pagecount; i++) {
HttpGet httpget = new HttpGet(urisToGet[i]);
config(httpget);
// 启动线程抓取
executors
.execute(new GetRunnable(urisToGet[i], countDownLatch));
}
countDownLatch.await();
executors.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("线程" + Thread.currentThread().getName() + ","
+ System.currentTimeMillis() + ", 所有线程已完成,开始进入下一步!");
}
long end = System.currentTimeMillis();
System.out.println("consume -> " + (end - start));
}
static class GetRunnable implements Runnable {
private CountDownLatch countDownLatch;
private String url;
public GetRunnable(String url, CountDownLatch countDownLatch) {
this.url = url;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
System.out.println(HttpClientUtil.get(url));
} finally {
countDownLatch.countDown();
}
}
}
}
http普通连接 post、get
public static Result httpsRequest(String requestUrl, String requestheader, String requestparams,Boolean retry) throws Exception{
// logger.info("req---->:" + requestMethod + requestStr);
Boolean ret = retry;
HttpsURLConnection httpsConnection = null;
Result result = new Result();
try {
// 创建SSLContext
SSLContext sslContext = SSLContext.getInstance("SSL");
TrustManager[] tm = { new TrustManager() };
// 初始化
sslContext.init(null, tm, new java.security.SecureRandom());
// 获取SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
HostnameVerifier HostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String var1, SSLSession var2) {
return true;
}
};
JSONObject jsonparam = JSON.parseObject(requestparams);
Iterator<Map.Entry<String, Object>> para = jsonparam.entrySet().iterator();
StringBuffer urlparams = new StringBuffer(350);
while(para.hasNext()){
Map.Entry<String, Object> entry = para.next();
urlparams.append(entry.getKey()+"="+entry.getValue()+"&");
}
URL url = new URL(requestUrl+"?"+urlparams);
httpsConnection = (HttpsURLConnection) url.openConnection();
httpsConnection.setDoOutput(false);
httpsConnection.setDoInput(true);
httpsConnection.setConnectTimeout(60000);
httpsConnection.setReadTimeout(60000);
httpsConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
httpsConnection.setRequestProperty("Charset", "UTF-8");
JSONObject jsonheader = JSON.parseObject(requestheader);
Iterator<Map.Entry<String, Object>> headers = jsonheader.entrySet().iterator();
while(headers.hasNext()){
Map.Entry<String, Object> entry = headers.next();
httpsConnection.setRequestProperty(entry.getKey(), entry.getValue().toString());
}
httpsConnection.setRequestProperty("User-Agent", "Client identifier");
httpsConnection.setRequestMethod("GET");
/*
* httpsConnection.setUseCaches(false);
* httpsConnection.setRequestMethod(requestMethod);
*/
// 设置当前实例使用的SSLSoctetFactory
httpsConnection.setSSLSocketFactory(ssf);
httpsConnection.setHostnameVerifier(HostnameVerifier);
// System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
httpsConnection.connect();
// 往服务器端写内容
// 读取服务器端返回的内容
InputStream inputStream = httpsConnection.getInputStream();
try{
inputStream = httpsConnection.getInputStream();
}catch (IOException e){
if(e.getMessage()!=null&&e.getMessage().contains("Server returned HTTP response code: 500 for URL")){
log.error("response from remote server error code 500!"+e.getMessage());
throw new Exception("错误码:500"+e.getMessage());
}else if(e.getMessage()!=null&&e.getMessage().contains("Address already in use: connect")){
log.error("response from remote server error:"+e.getMessage());
throw new Exception("错误:address in use"+e.getMessage());
}
}
if (httpsConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
// logger.error("connect ezcs service failed: " + httpsConnection.getResponseCode());
JSONObject responseJson = new JSONObject();
responseJson.put("result","error:code-"+httpsConnection.getResponseCode());
result.setCode(-1);
result.setData("error:code-"+httpsConnection.getResponseCode());
result.setMsg("失败");
return result;
}
InputStreamReader inputReader = new InputStreamReader(inputStream,"utf-8");
BufferedReader bufferReader = new BufferedReader(inputReader);
StringBuffer sb = new StringBuffer();
String inputLine = null;
while ((inputLine = bufferReader.readLine()) != null) {
sb.append(inputLine+"\n");
}
bufferReader.close();
inputReader.close();
inputStream.close();
// String response = readResponse(inputStream);
// Utils.convertStreamToString(inputStream, "utf-8");
// log.debug("response from service: " + response);
result.setCode(0);
result.setData(sb);
result.setMsg("成功");
return result;
}finally {
if (httpsConnection != null) {
httpsConnection.disconnect();
}
}
private static String readResponse(InputStream inputStream) throws Exception {
byte[] responseBytes = new byte[0];
while(true) {
byte[] readedBytes = new byte[1024];
int readedCount = inputStream.read(readedBytes);
if (readedCount <= 0) {
StringBuilder readResponse = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(responseBytes), StandardCharsets.UTF_8));
Throwable var17 = null;
try {
for(String line = br.readLine(); line != null; line = br.readLine()) {
readResponse.append(line).append("\r\n");
}
} catch (Throwable var13) {
var17 = var13;
throw var13;
} finally {
if (br != null) {
if (var17 != null) {
try {
br.close();
} catch (Throwable var12) {
var17.addSuppressed(var12);
}
} else {
br.close();
}
}
}
return readResponse.toString();
}
byte[] newBytes = new byte[responseBytes.length + readedCount];
System.arraycopy(responseBytes, 0, newBytes, 0, responseBytes.length);
System.arraycopy(readedBytes, 0, newBytes, responseBytes.length, readedCount);
responseBytes = newBytes;
}
}
static class TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}