HttpClientHelper.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. package com.happy.Unitil_elc;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpHost;
  4. import org.apache.http.NameValuePair;
  5. import org.apache.http.client.config.RequestConfig;
  6. import org.apache.http.client.entity.UrlEncodedFormEntity;
  7. import org.apache.http.client.methods.CloseableHttpResponse;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.client.methods.HttpPost;
  10. import org.apache.http.config.Registry;
  11. import org.apache.http.config.RegistryBuilder;
  12. import org.apache.http.config.SocketConfig;
  13. import org.apache.http.conn.socket.ConnectionSocketFactory;
  14. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  15. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  16. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  17. import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
  18. import org.apache.http.entity.StringEntity;
  19. import org.apache.http.impl.client.CloseableHttpClient;
  20. import org.apache.http.impl.client.HttpClientBuilder;
  21. import org.apache.http.impl.client.HttpClients;
  22. import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
  23. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  24. import org.apache.http.message.BasicHeader;
  25. import org.apache.http.message.BasicNameValuePair;
  26. import org.apache.http.protocol.HTTP;
  27. import org.apache.http.ssl.SSLContexts;
  28. import org.apache.http.util.EntityUtils;
  29. import org.slf4j.Logger;
  30. import org.slf4j.LoggerFactory;
  31. import javax.net.ssl.SSLContext;
  32. import java.io.IOException;
  33. import java.nio.charset.Charset;
  34. import java.util.ArrayList;
  35. import java.util.HashMap;
  36. import java.util.List;
  37. import java.util.Map;
  38. public class HttpClientHelper {
  39. private static final Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);
  40. private static PoolingHttpClientConnectionManager poolConnManager = null;
  41. private int maxTotalPool = 200;
  42. private int maxConPerRoute = 20;
  43. private int socketTimeout = 100000;
  44. private int connectionRequestTimeout = 90000;
  45. private int connectTimeout = 90000;
  46. // 代理信息
  47. public static String proxy_ip;
  48. public static int proxy_port;
  49. private static HttpClientHelper httpClientHelper = null;
  50. private HttpClientHelper() {
  51. init();
  52. }
  53. private static synchronized void syncInit() {
  54. if (httpClientHelper == null) {
  55. httpClientHelper = new HttpClientHelper();
  56. }
  57. }
  58. public static HttpClientHelper getInstance(String proxyIp, Integer proxyPort) {
  59. proxy_port = proxyPort;
  60. proxy_ip = proxyIp;
  61. if (httpClientHelper == null) {
  62. syncInit();
  63. }
  64. return httpClientHelper;
  65. }
  66. public static HttpClientHelper getInstance() {
  67. if (httpClientHelper == null) {
  68. syncInit();
  69. }
  70. return httpClientHelper;
  71. }
  72. public PoolingHttpClientConnectionManager getConnManager() {
  73. PoolingHttpClientConnectionManager cm = null;
  74. try {
  75. SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
  76. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);
  77. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http",
  78. PlainConnectionSocketFactory.getSocketFactory()).register("https",
  79. sslsf).build();
  80. cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  81. // 将最大连接数增加到200
  82. cm.setMaxTotal(maxTotalPool);
  83. // 将每个路由基础的连接增加到20
  84. cm.setDefaultMaxPerRoute(maxConPerRoute);
  85. } catch (Exception e) {
  86. logger.error("InterfacePhpUtilManager init Exception" + e.toString());
  87. }
  88. return cm;
  89. }
  90. public void init() {
  91. try {
  92. SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
  93. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);
  94. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http",
  95. PlainConnectionSocketFactory.getSocketFactory()).register("https",
  96. sslsf).build();
  97. poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  98. // Increase max total connection to 200
  99. poolConnManager.setMaxTotal(maxTotalPool);
  100. // Increase default max connection per route to 20
  101. poolConnManager.setDefaultMaxPerRoute(maxConPerRoute);
  102. SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
  103. poolConnManager.setDefaultSocketConfig(socketConfig);
  104. } catch (Exception e) {
  105. logger.error("InterfacePhpUtilManager init Exception" + e.toString());
  106. }
  107. }
  108. public CloseableHttpClient getConnection() {
  109. RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
  110. HttpClientBuilder httpClientBuilder = HttpClients.custom();
  111. httpClientBuilder.setConnectionManager(poolConnManager).setDefaultRequestConfig(requestConfig);// set proxy
  112. if (!StringUtil.isEmpty(proxy_ip) && proxy_port > 0) {
  113. HttpHost proxy = new HttpHost(proxy_ip, proxy_port);
  114. DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
  115. httpClientBuilder.setRoutePlanner(routePlanner);
  116. }
  117. CloseableHttpClient httpClient = httpClientBuilder.build();
  118. if (poolConnManager != null && poolConnManager.getTotalStats() != null) {
  119. logger.info("now client pool " + poolConnManager.getTotalStats().toString());
  120. }
  121. return httpClient;
  122. }
  123. /**
  124. * 发送 GET 请求(HTTP),不带输入数据
  125. */
  126. public String doGet(String url) {
  127. return doGet(url, new HashMap<String,String>());
  128. }
  129. /**
  130. * 发送 GET 请求(HTTP),K-V形式
  131. */
  132. public String doGet(String url, Map<String, String> params) {
  133. String apiUrl = url;
  134. StringBuffer param = new StringBuffer();
  135. int i = 0;
  136. for (String key : params.keySet()) {
  137. if (i == 0) {
  138. param.append("?");
  139. } else {
  140. param.append("&");
  141. }
  142. param.append(key).append("=").append(params.get(key));
  143. i++;
  144. }
  145. apiUrl += param;
  146. logger.info(apiUrl);
  147. String result = null;
  148. CloseableHttpClient httpClient = getConnection();
  149. CloseableHttpResponse response = null;
  150. HttpGet httpPost = null;
  151. try {
  152. httpPost = new HttpGet(apiUrl);
  153. response = httpClient.execute(httpPost);
  154. int status = response.getStatusLine().getStatusCode();
  155. logger.info("http request url : " + url + " status : " + status);
  156. if (status >= 200 && status < 300) {
  157. HttpEntity entity = response.getEntity();
  158. if (entity != null) {
  159. result = EntityUtils.toString(response.getEntity(), "UTF-8");
  160. logger.info("Request result : " + result);
  161. }
  162. }
  163. EntityUtils.consume(response.getEntity());
  164. response.close();
  165. return result;
  166. } catch (IOException e) {
  167. logger.error(e.getMessage(), e);
  168. } finally {
  169. httpPost.releaseConnection();
  170. if (response != null) {
  171. try {
  172. EntityUtils.consume(response.getEntity());
  173. response.close();
  174. } catch (IOException e) {
  175. logger.error(e.getMessage(), e);
  176. }
  177. }
  178. }
  179. return result;
  180. }
  181. public String doPost(String url) {
  182. return doPost(url, new HashMap<String, String>());
  183. }
  184. /**
  185. * 发送 POST json
  186. *
  187. * @param url 接口URL
  188. */
  189. public String doPostJson(String url, String jsonstr) {
  190. String result = null;
  191. HttpPost httpPost = new HttpPost(url);
  192. CloseableHttpClient httpClient = getConnection();
  193. CloseableHttpResponse response = null;
  194. try {
  195. StringEntity se = new StringEntity(jsonstr, Charset.forName("UTF-8"));
  196. se.setContentType("text/json");
  197. se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
  198. httpPost.setEntity(se);
  199. response = httpClient.execute(httpPost);
  200. int status = response.getStatusLine().getStatusCode();
  201. logger.info("http request url : " + url + " status : " + status);
  202. if (status >= 200 && status < 300) {
  203. HttpEntity entity = response.getEntity();
  204. if (entity != null) {
  205. result = EntityUtils.toString(response.getEntity(), "UTF-8");
  206. logger.info("Request result : " + result);
  207. }
  208. }
  209. EntityUtils.consume(response.getEntity());
  210. response.close();
  211. return result;
  212. } catch (IOException e) {
  213. logger.error(e.getMessage(), e);
  214. } finally {
  215. httpPost.releaseConnection();
  216. if (response != null) {
  217. try {
  218. EntityUtils.consume(response.getEntity());
  219. response.close();
  220. } catch (IOException e) {
  221. logger.error(e.getMessage(), e);
  222. }
  223. }
  224. }
  225. return result;
  226. }
  227. /**
  228. * 发送 POST 请求(HTTP),K-V形式
  229. *
  230. * @param url 接口URL
  231. * @param params 参数map
  232. * @return
  233. */
  234. public String doPost(String url, Map<String, String> params) {
  235. String result = null;
  236. HttpPost httpPost = new HttpPost(url);
  237. CloseableHttpClient httpClient = getConnection();
  238. CloseableHttpResponse response = null;
  239. try {
  240. List<NameValuePair> pairList = new ArrayList<>(params.size());
  241. for (Map.Entry<String, String> entry : params.entrySet()) {
  242. NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
  243. pairList.add(pair);
  244. }
  245. httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
  246. response = httpClient.execute(httpPost);
  247. int status = response.getStatusLine().getStatusCode();
  248. logger.info("http request url : " + url + " status : " + status);
  249. if (status >= 200 && status < 300) {
  250. HttpEntity entity = response.getEntity();
  251. if (entity != null) {
  252. result = EntityUtils.toString(response.getEntity(), "UTF-8");
  253. logger.info("Request result : " + result);
  254. }
  255. }
  256. EntityUtils.consume(response.getEntity());
  257. response.close();
  258. return result;
  259. } catch (IOException e) {
  260. logger.error(e.getMessage(), e);
  261. } finally {
  262. httpPost.releaseConnection();
  263. if (response != null) {
  264. try {
  265. EntityUtils.consume(response.getEntity());
  266. response.close();
  267. } catch (IOException e) {
  268. logger.error(e.getMessage(), e);
  269. }
  270. }
  271. }
  272. return result;
  273. }
  274. /**
  275. * 发送 POST 请求(HTTP),K-V形式
  276. *
  277. * @param url 接口URL
  278. * @param params 参数map
  279. * @return
  280. */
  281. public String doPost(String url, Map<String, String> params, String token) {
  282. String result = null;
  283. HttpPost httpPost = new HttpPost(url);
  284. CloseableHttpClient httpClient = getConnection();
  285. CloseableHttpResponse response = null;
  286. try {
  287. List<NameValuePair> pairList = new ArrayList<>(params.size());
  288. for (Map.Entry<String, String> entry : params.entrySet()) {
  289. NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
  290. pairList.add(pair);
  291. }
  292. httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
  293. httpPost.addHeader("token", token);
  294. response = httpClient.execute(httpPost);
  295. int status = response.getStatusLine().getStatusCode();
  296. logger.info("http request url : " + url + " status : " + status);
  297. if (status >= 200 && status < 300) {
  298. HttpEntity entity = response.getEntity();
  299. if (entity != null) {
  300. result = EntityUtils.toString(response.getEntity(), "UTF-8");
  301. logger.info("Request result : " + result);
  302. }
  303. }
  304. EntityUtils.consume(response.getEntity());
  305. response.close();
  306. return result;
  307. } catch (IOException e) {
  308. logger.error(e.getMessage(), e);
  309. } finally {
  310. httpPost.releaseConnection();
  311. if (response != null) {
  312. try {
  313. EntityUtils.consume(response.getEntity());
  314. response.close();
  315. } catch (IOException e) {
  316. logger.error(e.getMessage(), e);
  317. }
  318. }
  319. }
  320. return result;
  321. }
  322. }