HttpUtils.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. package com.malk.chuizi.utils;
  2. import com.alibaba.fastjson.JSON;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.apache.http.HttpEntity;
  5. import org.apache.http.client.config.RequestConfig;
  6. import org.apache.http.client.methods.CloseableHttpResponse;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.config.Registry;
  10. import org.apache.http.config.RegistryBuilder;
  11. import org.apache.http.config.SocketConfig;
  12. import org.apache.http.conn.DnsResolver;
  13. import org.apache.http.conn.HttpConnectionFactory;
  14. import org.apache.http.conn.ManagedHttpClientConnection;
  15. import org.apache.http.conn.routing.HttpRoute;
  16. import org.apache.http.conn.socket.ConnectionSocketFactory;
  17. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  18. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  19. import org.apache.http.entity.ContentType;
  20. import org.apache.http.entity.StringEntity;
  21. import org.apache.http.impl.DefaultConnectionReuseStrategy;
  22. import org.apache.http.impl.client.CloseableHttpClient;
  23. import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
  24. import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
  25. import org.apache.http.impl.client.HttpClients;
  26. import org.apache.http.impl.conn.ManagedHttpClientConnectionFactory;
  27. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  28. import org.apache.http.impl.conn.SystemDefaultDnsResolver;
  29. import org.apache.http.impl.io.DefaultHttpRequestWriterFactory;
  30. import org.apache.http.impl.io.DefaultHttpResponseParserFactory;
  31. import org.apache.http.util.EntityUtils;
  32. import java.nio.charset.Charset;
  33. import java.util.Map;
  34. import java.util.concurrent.TimeUnit;
  35. /**
  36. * http请求封装
  37. *
  38. * @author lh
  39. * @date 2022-09-23
  40. */
  41. @Slf4j
  42. public class HttpUtils {
  43. /**
  44. * 默认请求类型
  45. */
  46. private static final String DEFAULT_CONTENT_TYPE = "application/json";
  47. /**
  48. * 默认编码
  49. */
  50. private static final String DEFAULT_ENCODING = "utf-8";
  51. /**
  52. * GBK编码
  53. */
  54. private static final String GBK_ENCODING = "GBK";
  55. /**
  56. * 默认超时时间
  57. */
  58. private static final int DEFAULT_TIME_OUT = 60;
  59. private static PoolingHttpClientConnectionManager manager = null;
  60. private static CloseableHttpClient httpClient = null;
  61. /**
  62. * 获取httpclient对象
  63. *
  64. * @return
  65. */
  66. public static synchronized CloseableHttpClient getHttpClient(int timeOut) {
  67. if (null == httpClient) {
  68. log.info("============================================创建");
  69. // 注册访问协议相关的socket工厂
  70. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  71. .register("http", PlainConnectionSocketFactory.INSTANCE)
  72. .register("https", SSLConnectionSocketFactory.getSystemSocketFactory())
  73. .build();
  74. // httpConnection工厂
  75. HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connectionFactory =
  76. new ManagedHttpClientConnectionFactory(DefaultHttpRequestWriterFactory.INSTANCE
  77. , DefaultHttpResponseParserFactory.INSTANCE);
  78. // DNS解析器
  79. DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE;
  80. // 创建池化连接管理器
  81. manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connectionFactory, dnsResolver);
  82. // socket配置
  83. SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
  84. manager.setDefaultSocketConfig(socketConfig);
  85. // 连接池最大连接数
  86. manager.setMaxTotal(300);
  87. manager.setDefaultMaxPerRoute(200);
  88. // 5s检测一次连接池连接
  89. manager.setValidateAfterInactivity(5 * 1000);
  90. // 默认请求配置
  91. RequestConfig requestConfig = RequestConfig.custom()
  92. // 连接超时时间
  93. .setConnectTimeout(timeOut * 1000)
  94. // 等待数据超时时间
  95. .setSocketTimeout(timeOut * 1000)
  96. // 从连接池获取连接超时时间
  97. .setConnectionRequestTimeout(timeOut * 1000)
  98. .build();
  99. // 创建httpclient
  100. httpClient = HttpClients.custom()
  101. .setConnectionManager(manager)
  102. // 连接池不共享
  103. .setConnectionManagerShared(false)
  104. // 定期回收空闲连接
  105. .evictIdleConnections(timeOut, TimeUnit.SECONDS)
  106. // 定期回收过期连接
  107. .evictExpiredConnections()
  108. .setConnectionTimeToLive(timeOut, TimeUnit.SECONDS)
  109. // 设置默认请求
  110. .setDefaultRequestConfig(requestConfig)
  111. // 连接重用策略
  112. .setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE)
  113. // 长连接配置
  114. .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)
  115. // 设置重试次数
  116. .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
  117. .build();
  118. // jvm停止或重启时,关闭连接池释放连接
  119. Runtime.getRuntime().addShutdownHook(new Thread() {
  120. @Override
  121. public void run() {
  122. try {
  123. if (null != httpClient) {
  124. httpClient.close();
  125. }
  126. } catch (Exception e) {
  127. log.error("httpclient关闭异常:{}", e);
  128. }
  129. }
  130. });
  131. }
  132. return httpClient;
  133. }
  134. /**
  135. * http请求
  136. *
  137. * @param url
  138. * @param params
  139. * @return
  140. */
  141. public static String httpPost(String url, Map params,Map<String,String> headers) {
  142. log.info("POST请求url:{}", url);
  143. log.info("POST请求参数:{}",JSON.toJSONString(params));
  144. CloseableHttpClient httpClient = getHttpClient(DEFAULT_TIME_OUT);
  145. HttpPost httpPost = new HttpPost(url);
  146. if (null != headers){
  147. for (String key:headers.keySet()){
  148. httpPost.setHeader(key,headers.get(key).toString());
  149. }
  150. }
  151. String json = JSON.toJSONString(params);
  152. StringEntity stringEntity = new StringEntity(json, DEFAULT_ENCODING);
  153. stringEntity.setContentEncoding(DEFAULT_ENCODING);
  154. httpPost.setEntity(stringEntity);
  155. String result = null;
  156. try (CloseableHttpResponse response = httpClient.execute(httpPost);) {
  157. HttpEntity entity = response.getEntity();
  158. if (null != entity) {
  159. result = EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset());
  160. EntityUtils.consume(entity);
  161. }
  162. } catch (Exception e) {
  163. log.error("接口请求异常:{}", e);
  164. }
  165. return result;
  166. }
  167. /**
  168. * http请求(POST请求,GBK编码)
  169. *
  170. * @param url
  171. * @param params
  172. * @return
  173. */
  174. public static String httpPostGBK(String url, Map params,Map<String,String> headers) {
  175. log.info("POST请求url:{}", url);
  176. log.info("POST请求参数:{}",JSON.toJSONString(params));
  177. CloseableHttpClient httpClient = getHttpClient(DEFAULT_TIME_OUT);
  178. HttpPost httpPost = new HttpPost(url);
  179. if (null != headers){
  180. for (String key:headers.keySet()){
  181. httpPost.setHeader(key,headers.get(key).toString());
  182. }
  183. }
  184. String json = JSON.toJSONString(params);
  185. StringEntity stringEntity = new StringEntity(json, DEFAULT_ENCODING);
  186. stringEntity.setContentEncoding(DEFAULT_ENCODING);
  187. httpPost.setEntity(stringEntity);
  188. String result = null;
  189. try (CloseableHttpResponse response = httpClient.execute(httpPost);) {
  190. HttpEntity entity = response.getEntity();
  191. if (null != entity) {
  192. // result = EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset());
  193. result = EntityUtils.toString(entity, Charset.defaultCharset());
  194. EntityUtils.consume(entity);
  195. }
  196. } catch (Exception e) {
  197. log.error("接口请求异常:{}", e);
  198. }
  199. return result;
  200. }
  201. /**
  202. * http请求(POST请求,GBK编码)
  203. *
  204. * @param url
  205. * @param params
  206. * @param headers
  207. * @param timeOut 超时时间
  208. * @return
  209. */
  210. public static String httpPostGBK(String url, Map params, Map<String, String> headers, int timeOut) {
  211. log.info("POST请求url:{}", url);
  212. log.info("POST请求参数:{}", JSON.toJSONString(params));
  213. CloseableHttpClient httpClient = getHttpClient(timeOut);
  214. HttpPost httpPost = new HttpPost(url);
  215. if (null != headers) {
  216. for (String key : headers.keySet()) {
  217. httpPost.setHeader(key, headers.get(key).toString());
  218. }
  219. }
  220. String json = JSON.toJSONString(params);
  221. StringEntity stringEntity = new StringEntity(json, DEFAULT_ENCODING);
  222. stringEntity.setContentEncoding(DEFAULT_ENCODING);
  223. httpPost.setEntity(stringEntity);
  224. String result = null;
  225. try (CloseableHttpResponse response = httpClient.execute(httpPost);) {
  226. HttpEntity entity = response.getEntity();
  227. if (null != entity) {
  228. // result = EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset());
  229. result = EntityUtils.toString(entity, Charset.defaultCharset());
  230. EntityUtils.consume(entity);
  231. }
  232. } catch (Exception e) {
  233. log.error("接口请求异常:{}", e);
  234. }
  235. return result;
  236. }
  237. /**
  238. * http请求
  239. *
  240. * @param url
  241. * @return
  242. */
  243. public static String httpGet(String url) {
  244. log.info("请求url:{}", url);
  245. CloseableHttpClient httpClient = getHttpClient(DEFAULT_TIME_OUT);
  246. HttpGet httpGet = new HttpGet(url);
  247. String result = null;
  248. try (CloseableHttpResponse response = httpClient.execute(httpGet);) {
  249. HttpEntity entity = response.getEntity();
  250. if (null != entity) {
  251. result = EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset());
  252. EntityUtils.consume(entity);
  253. }
  254. } catch (Exception e) {
  255. log.error("接口请求异常:{}", e);
  256. }
  257. return result;
  258. }
  259. }