|
@@ -0,0 +1,372 @@
|
|
|
+package com.ruoyi.web.controller.monitoringAlarms.utils;
|
|
|
+
|
|
|
+
|
|
|
+import org.apache.commons.codec.binary.Base64;
|
|
|
+import org.apache.commons.io.IOUtils;
|
|
|
+import org.apache.commons.lang3.StringUtils;
|
|
|
+import org.apache.http.*;
|
|
|
+import org.apache.http.client.config.RequestConfig;
|
|
|
+import org.apache.http.client.config.RequestConfig.Builder;
|
|
|
+import org.apache.http.client.entity.UrlEncodedFormEntity;
|
|
|
+import org.apache.http.client.methods.HttpGet;
|
|
|
+import org.apache.http.client.methods.HttpPost;
|
|
|
+import org.apache.http.client.protocol.HttpClientContext;
|
|
|
+import org.apache.http.config.Registry;
|
|
|
+import org.apache.http.config.RegistryBuilder;
|
|
|
+import org.apache.http.config.SocketConfig;
|
|
|
+import org.apache.http.conn.ConnectTimeoutException;
|
|
|
+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.conn.ssl.SSLContextBuilder;
|
|
|
+import org.apache.http.conn.ssl.TrustStrategy;
|
|
|
+import org.apache.http.conn.ssl.X509HostnameVerifier;
|
|
|
+import org.apache.http.entity.ContentType;
|
|
|
+import org.apache.http.entity.StringEntity;
|
|
|
+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 javax.net.ssl.*;
|
|
|
+import java.io.IOException;
|
|
|
+import java.io.InterruptedIOException;
|
|
|
+import java.net.SocketTimeoutException;
|
|
|
+import java.net.UnknownHostException;
|
|
|
+import java.security.GeneralSecurityException;
|
|
|
+import java.security.cert.CertificateException;
|
|
|
+import java.security.cert.X509Certificate;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Map;
|
|
|
+import java.util.Set;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 2020-4-3 by houxainyong 添加http 连接池,兼容 http 和Https
|
|
|
+ */
|
|
|
+public class HttpUtil {
|
|
|
+
|
|
|
+
|
|
|
+ public static final int connTimeout = 10000;
|
|
|
+ public static final int readTimeout = 10000;
|
|
|
+
|
|
|
+ public static final String charset = "UTF-8";
|
|
|
+ private static final int CONNECT_TIMEOUT = 5000;//设置超时毫秒数
|
|
|
+
|
|
|
+ private static final int SOCKET_TIMEOUT = 10000;//设置传输毫秒数
|
|
|
+
|
|
|
+ private static final int REQUESTCONNECT_TIMEOUT = 3000;//获取请求超时毫秒数
|
|
|
+
|
|
|
+ private static final int CONNECT_TOTAL = 400;//最大连接数
|
|
|
+
|
|
|
+ private static final int CONNECT_ROUTE = 120;//设置每个路由的基础连接数
|
|
|
+
|
|
|
+ private static final int VALIDATE_TIME = 30000;//设置重用连接时间
|
|
|
+
|
|
|
+ private static final String RESPONSE_CONTENT = "通信失败";
|
|
|
+
|
|
|
+ private static PoolingHttpClientConnectionManager manager = null;
|
|
|
+
|
|
|
+ private static CloseableHttpClient client = null;
|
|
|
+
|
|
|
+ static {
|
|
|
+ ConnectionSocketFactory csf = PlainConnectionSocketFactory.getSocketFactory();
|
|
|
+ LayeredConnectionSocketFactory lsf = createSSLConnSocketFactory();
|
|
|
+ Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
|
|
|
+ .register("http", csf).register("https", lsf).build();
|
|
|
+ manager = new PoolingHttpClientConnectionManager(registry);
|
|
|
+ manager.setMaxTotal(CONNECT_TOTAL);
|
|
|
+ manager.setDefaultMaxPerRoute(CONNECT_ROUTE);
|
|
|
+ manager.setValidateAfterInactivity(VALIDATE_TIME);
|
|
|
+ SocketConfig config = SocketConfig.custom().setSoTimeout(SOCKET_TIMEOUT).build();
|
|
|
+ manager.setDefaultSocketConfig(config);
|
|
|
+ RequestConfig requestConf = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
|
|
|
+ .setConnectionRequestTimeout(REQUESTCONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
|
|
|
+ client = HttpClients.custom().setConnectionManager(manager).setDefaultRequestConfig(requestConf).setRetryHandler(
|
|
|
+ //实现了HttpRequestRetryHandler接口的
|
|
|
+ (exception, executionCount, context) -> {
|
|
|
+ if (executionCount >= 2)
|
|
|
+ return false;
|
|
|
+ if (exception instanceof NoHttpResponseException)//如果服务器断掉了连接那么重试
|
|
|
+ return true;
|
|
|
+ if (exception instanceof SSLHandshakeException)//不重试握手异常
|
|
|
+ return false;
|
|
|
+ if (exception instanceof InterruptedIOException)//IO传输中断重试
|
|
|
+ return true;
|
|
|
+ if (exception instanceof UnknownHostException)//未知服务器
|
|
|
+ return false;
|
|
|
+ if (exception instanceof ConnectTimeoutException)//超时就重试
|
|
|
+ return true;
|
|
|
+ if (exception instanceof SSLException)
|
|
|
+ return false;
|
|
|
+
|
|
|
+ HttpClientContext cliContext = HttpClientContext.adapt(context);
|
|
|
+ HttpRequest request = cliContext.getRequest();
|
|
|
+ if (!(request instanceof HttpEntityEnclosingRequest))
|
|
|
+ return true;
|
|
|
+ return false;
|
|
|
+ }).build();
|
|
|
+ if (manager != null && manager.getTotalStats() != null) {
|
|
|
+ System.out.println("连接池池状态:" + manager.getTotalStats().toString());
|
|
|
+ //LOG.info("连接池池状态:" + manager.getTotalStats().toString());
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ static SSLConnectionSocketFactory createSSLConnSocketFactory() {
|
|
|
+
|
|
|
+ SSLConnectionSocketFactory sslsf = null;
|
|
|
+ try {
|
|
|
+ SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
|
|
|
+ public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ }).build();
|
|
|
+
|
|
|
+ sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
|
|
|
+ @Override
|
|
|
+ public boolean verify(String arg0, SSLSession arg1) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void verify(String host, SSLSocket ssl)
|
|
|
+ throws IOException {
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void verify(String host, X509Certificate cert)
|
|
|
+ throws SSLException {
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void verify(String host, String[] cns,
|
|
|
+ String[] subjectAlts) throws SSLException {
|
|
|
+ }
|
|
|
+ });
|
|
|
+
|
|
|
+ return sslsf;
|
|
|
+
|
|
|
+ } catch (GeneralSecurityException e) {
|
|
|
+ System.out.println(e);
|
|
|
+ //LOG.error(e.getMessage());
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String postParameters(String url, String parameterStr, Map<String, String> headers) throws Exception {
|
|
|
+ return post(url, parameterStr, "application/json", charset, connTimeout, readTimeout, headers);
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception {
|
|
|
+ return post(url, parameterStr, "application/json", charset, connTimeout, readTimeout, null);
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String postParameters(String url, String parameterStr, String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception {
|
|
|
+ return post(url, parameterStr, "application/json", charset, connTimeout, readTimeout, null);
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException,
|
|
|
+ SocketTimeoutException, Exception {
|
|
|
+ return postForm(url, params, null, connTimeout, readTimeout);
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String postParameters(String url, Map<String, String> params, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException,
|
|
|
+ SocketTimeoutException, Exception {
|
|
|
+ return postForm(url, params, null, connTimeout, readTimeout);
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String postFormParameters(String url, Map<String, String> headers, Map<String, String> params) throws ConnectTimeoutException,
|
|
|
+ SocketTimeoutException, Exception {
|
|
|
+ return postForm(url, params, headers, connTimeout, readTimeout);
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String get(String url) throws Exception {
|
|
|
+ return get(url, charset, null, null);
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String get(String url, String charset) throws Exception {
|
|
|
+ return get(url, charset, connTimeout, readTimeout);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 发送一个 Post 请求, 使用指定的字符集编码.
|
|
|
+ *
|
|
|
+ * @param url
|
|
|
+ * @param body RequestBody
|
|
|
+ * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3
|
|
|
+ * @param charset 编码
|
|
|
+ * @param connTimeout 建立链接超时时间,毫秒.
|
|
|
+ * @param readTimeout 响应超时时间,毫秒.
|
|
|
+ * @return ResponseBody, 使用指定的字符集编码.
|
|
|
+ * @throws ConnectTimeoutException 建立链接超时异常
|
|
|
+ * @throws SocketTimeoutException 响应超时
|
|
|
+ * @throws Exception
|
|
|
+ */
|
|
|
+ public static String post(String url, String body, String mimeType, String charset, Integer connTimeout, Integer readTimeout, Map<String, String> headers)
|
|
|
+ throws ConnectTimeoutException, SocketTimeoutException, Exception {
|
|
|
+
|
|
|
+ HttpPost post = new HttpPost(url);
|
|
|
+ if (headers != null) {
|
|
|
+ for (Map.Entry<String, String> item : headers.entrySet()) {
|
|
|
+ post.setHeader(item.getKey(), item.getValue());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ String result = "";
|
|
|
+ try {
|
|
|
+ if (StringUtils.isNotBlank(body)) {
|
|
|
+ HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
|
|
|
+ post.setEntity(entity);
|
|
|
+ }
|
|
|
+ // 设置参数
|
|
|
+ Builder customReqConf = RequestConfig.custom();
|
|
|
+ if (connTimeout != null) {
|
|
|
+ customReqConf.setConnectTimeout(connTimeout);
|
|
|
+ }
|
|
|
+ if (readTimeout != null) {
|
|
|
+ customReqConf.setSocketTimeout(readTimeout);
|
|
|
+ }
|
|
|
+ post.setConfig(customReqConf.build());
|
|
|
+
|
|
|
+ HttpResponse res = client.execute(post);
|
|
|
+
|
|
|
+ result = IOUtils.toString(res.getEntity().getContent(), charset);
|
|
|
+ } finally {
|
|
|
+ if(post!=null){
|
|
|
+ post.releaseConnection();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 提交form表单
|
|
|
+ *
|
|
|
+ * @param url
|
|
|
+ * @param params
|
|
|
+ * @param connTimeout
|
|
|
+ * @param readTimeout
|
|
|
+ * @return
|
|
|
+ * @throws ConnectTimeoutException
|
|
|
+ * @throws SocketTimeoutException
|
|
|
+ * @throws Exception
|
|
|
+ */
|
|
|
+ public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException,
|
|
|
+ SocketTimeoutException, Exception {
|
|
|
+
|
|
|
+ HttpPost post = new HttpPost(url);
|
|
|
+ try {
|
|
|
+ if (params != null && !params.isEmpty()) {
|
|
|
+ List<NameValuePair> formParams = new ArrayList<NameValuePair>();
|
|
|
+ Set<Map.Entry<String, String>> entrySet = params.entrySet();
|
|
|
+ for (Map.Entry<String, String> entry : entrySet) {
|
|
|
+ formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
|
|
|
+ }
|
|
|
+ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
|
|
|
+ post.setEntity(entity);
|
|
|
+ }
|
|
|
+
|
|
|
+ if (headers != null && !headers.isEmpty()) {
|
|
|
+ for (Map.Entry<String, String> entry : headers.entrySet()) {
|
|
|
+ post.addHeader(entry.getKey(), entry.getValue());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ // 设置参数
|
|
|
+ Builder customReqConf = RequestConfig.custom();
|
|
|
+ if (connTimeout != null) {
|
|
|
+ customReqConf.setConnectTimeout(connTimeout);
|
|
|
+ }
|
|
|
+ if (readTimeout != null) {
|
|
|
+ customReqConf.setSocketTimeout(readTimeout);
|
|
|
+ }
|
|
|
+ post.setConfig(customReqConf.build());
|
|
|
+ HttpResponse res = client.execute(post);
|
|
|
+
|
|
|
+ return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
|
|
|
+ } finally {
|
|
|
+ if(post!=null){
|
|
|
+ post.releaseConnection();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ public static String encryptBASE64(String username,String password) {
|
|
|
+ byte[] key = (username+":"+password).getBytes();
|
|
|
+ return new String(Base64.encodeBase64(key));
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 发送一个 GET 请求
|
|
|
+ *
|
|
|
+ * @param url
|
|
|
+ * @param charset
|
|
|
+ * @param connTimeout 建立链接超时时间,毫秒.
|
|
|
+ * @param readTimeout 响应超时时间,毫秒.
|
|
|
+ * @return
|
|
|
+ * @throws ConnectTimeoutException 建立链接超时
|
|
|
+ * @throws SocketTimeoutException 响应超时
|
|
|
+ * @throws Exception
|
|
|
+ */
|
|
|
+ public static String get(String url, String charset, Integer connTimeout, Integer readTimeout)
|
|
|
+ throws ConnectTimeoutException, SocketTimeoutException, Exception {
|
|
|
+
|
|
|
+ String authorization = "Basic "+encryptBASE64("nginx","1q2w3e4r5t@");
|
|
|
+
|
|
|
+ HttpGet get = new HttpGet(url);
|
|
|
+ //get.addHeader("Authorization",authorization);
|
|
|
+ String result = "";
|
|
|
+ try {
|
|
|
+ // 设置参数
|
|
|
+ Builder customReqConf = RequestConfig.custom();
|
|
|
+ if (connTimeout != null) {
|
|
|
+ customReqConf.setConnectTimeout(connTimeout);
|
|
|
+ }
|
|
|
+ if (readTimeout != null) {
|
|
|
+ customReqConf.setSocketTimeout(readTimeout);
|
|
|
+ }
|
|
|
+ get.setConfig(customReqConf.build());
|
|
|
+
|
|
|
+ HttpResponse res = client.execute(get);
|
|
|
+
|
|
|
+
|
|
|
+ result = IOUtils.toString(res.getEntity().getContent(), charset);
|
|
|
+ } finally {
|
|
|
+ if(get!=null){
|
|
|
+ get.releaseConnection();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 从 response 里获取 charset
|
|
|
+ *
|
|
|
+ * @param ressponse
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ @SuppressWarnings("unused")
|
|
|
+ private static String getCharsetFromResponse(HttpResponse ressponse) {
|
|
|
+ // Content-Type:text/html; charset=GBK
|
|
|
+ if (ressponse.getEntity() != null && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {
|
|
|
+ String contentType = ressponse.getEntity().getContentType().getValue();
|
|
|
+ if (contentType.contains("charset=")) {
|
|
|
+ return contentType.substring(contentType.indexOf("charset=") + 8);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ public static void main(String[] args) {
|
|
|
+ try {
|
|
|
+ String str = HttpUtil.get("http://10.100.12.246:4040/8414eab8894541c5afdcb2d606c6f50b.jpg");
|
|
|
+ System.out.println(str);
|
|
|
+ }catch (Exception ex){
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+}
|