智能仲裁后端服务

HttpClientSender.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. package com.ruoyi.bestsign.utils;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.client.config.RequestConfig;
  4. import org.apache.http.client.methods.CloseableHttpResponse;
  5. import org.apache.http.client.methods.HttpGet;
  6. import org.apache.http.client.methods.HttpPost;
  7. import org.apache.http.config.Registry;
  8. import org.apache.http.config.RegistryBuilder;
  9. import org.apache.http.conn.socket.ConnectionSocketFactory;
  10. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  11. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  12. import org.apache.http.entity.StringEntity;
  13. import org.apache.http.impl.client.CloseableHttpClient;
  14. import org.apache.http.impl.client.HttpClients;
  15. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  16. import org.apache.http.util.EntityUtils;
  17. import javax.net.ssl.SSLContext;
  18. import javax.net.ssl.TrustManager;
  19. import javax.net.ssl.X509TrustManager;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.UnsupportedEncodingException;
  23. import java.net.MalformedURLException;
  24. import java.net.URL;
  25. import java.net.URLEncoder;
  26. import java.security.cert.CertificateException;
  27. import java.security.cert.X509Certificate;
  28. import java.util.HashMap;
  29. import java.util.Map;
  30. public class HttpClientSender {
  31. private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = null;
  32. private static Map<String, CloseableHttpClient> httpClients = new HashMap<String, CloseableHttpClient>();
  33. private static Object o = new Object();
  34. public static String sendHttpPost(String host, String method, String urlParams, String sendData) throws IOException {
  35. String requestUrl = host + method + urlParams;
  36. Map<String, Object> response = request("POST", requestUrl, sendData, null);
  37. int responseCode = Integer.parseInt(response.get("responseCode").toString());
  38. byte[] responseBytes = (byte[]) response.get("responseData");
  39. String responseString;
  40. try {
  41. responseString = new String(responseBytes, "UTF-8");
  42. } catch (UnsupportedEncodingException e) {
  43. responseString = new String(responseBytes);
  44. }
  45. //请求返回结果无论成功失败,http-status均为200
  46. if (responseCode == 200) {
  47. //返回结果
  48. return responseString;
  49. } else {
  50. throw new IOException(responseCode + ":" + responseString);
  51. }
  52. }
  53. public static byte[] sendHttpGet(String host, String method, String urlParams) throws IOException {
  54. String requestUrl = host + method + urlParams;
  55. Map<String, Object> response = request("GET", requestUrl, null, null);
  56. int responseCode = Integer.parseInt(response.get("responseCode").toString());
  57. byte[] responseBytes = (byte[]) response.get("responseData");
  58. //请求返回结果无论成功失败,http-status均为200
  59. if (responseCode == 200) {
  60. //返回结果
  61. return responseBytes;
  62. } else {
  63. throw new IOException(responseCode + "");
  64. }
  65. }
  66. public static String urlencode(String data) {
  67. return urlencode(data, "UTF-8");
  68. }
  69. public static String urlencode(String data, String charset) {
  70. try {
  71. return URLEncoder.encode(data, charset);
  72. } catch (UnsupportedEncodingException e) {
  73. throw new RuntimeException(e.getMessage(), e);
  74. }
  75. }
  76. public static Map<String, Object> request(String method, String url, Object sendData, Map<String, String> headers) throws IOException {
  77. String requestPath;
  78. try {
  79. requestPath = new URL(url).getPath();
  80. } catch (MalformedURLException e) {
  81. throw new RuntimeException(e.getMessage(), e);
  82. }
  83. CloseableHttpClient httpClient = getHttpClient(requestPath);
  84. Map<String, Object> response = null;
  85. if ("POST".equals(method)) {
  86. response = sendPost(httpClient, url, headers, sendData);
  87. } else {
  88. response = sendGet(httpClient, url, headers);
  89. }
  90. return response;
  91. }
  92. private static Map<String, Object> sendPost(CloseableHttpClient httpClient, String url, Map<String, String> headers, Object sendData) throws IOException {
  93. String tag = "[HttpRequester] [POST " + url + "]";
  94. int responseCode = -1;
  95. byte[] responseBytes = null;
  96. HttpPost request = new HttpPost(url);
  97. if (headers != null && headers.size() > 0) {
  98. for (String name : headers.keySet()) {
  99. String value = headers.get(name);
  100. request.setHeader(name, value);
  101. }
  102. }
  103. if (sendData != null) {
  104. StringEntity stringEntity = new StringEntity((String) sendData, "UTF-8");
  105. stringEntity.setContentType("application/json");
  106. request.setEntity(stringEntity);
  107. HttpEntity httpEntity = null;
  108. IOException exception = null;
  109. for (int i = 0; i < 3; i++) {
  110. try {
  111. CloseableHttpResponse response = httpClient.execute(request);
  112. responseCode = response.getStatusLine().getStatusCode();
  113. httpEntity = response.getEntity();
  114. String responseBody = EntityUtils.toString(httpEntity, "utf-8");
  115. if (responseBody != null) {
  116. responseBytes = responseBody.getBytes();
  117. } else {
  118. InputStream respStream = null;
  119. try {
  120. respStream = httpEntity.getContent();
  121. int respBodySize = respStream.available();
  122. if (respBodySize <= 0)
  123. throw new IOException("Invalid respBodySize: " + respBodySize);
  124. responseBytes = new byte[respBodySize];
  125. if (respStream.read(responseBytes) != respBodySize)
  126. throw new IOException("Read respBody Error");
  127. } catch (Exception e) {
  128. } finally {
  129. if (respStream != null) {
  130. respStream.close();
  131. }
  132. }
  133. }
  134. exception = null;
  135. break;
  136. } catch (UnsupportedOperationException e) {
  137. try {
  138. EntityUtils.consume(httpEntity);
  139. } catch (IOException e2) {
  140. }
  141. throw new RuntimeException(e.getMessage(), e);
  142. } catch (IOException e) {
  143. e.printStackTrace();
  144. exception = e;
  145. try {
  146. EntityUtils.consume(httpEntity);
  147. } catch (IOException e2) {
  148. }
  149. if (i < 2) {
  150. try {
  151. Thread.sleep(5);
  152. } catch (InterruptedException e2) {
  153. }
  154. }
  155. }
  156. }
  157. if (exception != null) {
  158. throw exception;
  159. }
  160. }
  161. Map<String, Object> response = new HashMap<String, Object>();
  162. response.put("responseCode", responseCode);
  163. response.put("responseData", responseBytes);
  164. String loggerResponseString = getLoggerString(responseBytes, 256);
  165. return response;
  166. }
  167. private static Map<String, Object> sendGet(CloseableHttpClient httpClient, String url, Map<String, String> headers) throws IOException {
  168. String tag = "[HttpRequester] [GET " + url + "]";
  169. int responseCode = -1;
  170. byte[] responseBytes = null;
  171. HttpGet request = new HttpGet(url);
  172. if (headers != null && headers.size() > 0) {
  173. for (String name : headers.keySet()) {
  174. String value = headers.get(name);
  175. request.setHeader(name, value);
  176. }
  177. }
  178. HttpEntity httpEntity = null;
  179. IOException exception = null;
  180. for (int i = 0; i < 3; i++) {
  181. try {
  182. CloseableHttpResponse response = httpClient.execute(request);
  183. responseCode = response.getStatusLine().getStatusCode();
  184. httpEntity = response.getEntity();
  185. byte[] responseBody = EntityUtils.toByteArray(httpEntity);
  186. if (responseBody != null) {
  187. responseBytes = responseBody;
  188. } else {
  189. InputStream respStream = null;
  190. try {
  191. respStream = httpEntity.getContent();
  192. int respBodySize = respStream.available();
  193. if (respBodySize <= 0)
  194. throw new IOException("Invalid respBodySize: " + respBodySize);
  195. responseBytes = new byte[respBodySize];
  196. if (respStream.read(responseBytes) != respBodySize)
  197. throw new IOException("Read respBody Error");
  198. } catch (Exception e) {
  199. } finally {
  200. if (respStream != null) {
  201. respStream.close();
  202. }
  203. }
  204. }
  205. exception = null;
  206. break;
  207. } catch (UnsupportedOperationException e) {
  208. try {
  209. EntityUtils.consume(httpEntity);
  210. } catch (IOException e2) {
  211. }
  212. throw new RuntimeException(e.getMessage(), e);
  213. } catch (IOException e) {
  214. e.printStackTrace();
  215. exception = e;
  216. try {
  217. EntityUtils.consume(httpEntity);
  218. } catch (IOException e2) {
  219. }
  220. if (i < 2) {
  221. try {
  222. Thread.sleep(5);
  223. } catch (InterruptedException e2) {
  224. }
  225. }
  226. }
  227. }
  228. if (exception != null) {
  229. throw exception;
  230. }
  231. Map<String, Object> response = new HashMap<String, Object>();
  232. response.put("responseCode", responseCode);
  233. response.put("responseData", responseBytes);
  234. String loggerResponseString = getLoggerString(responseBytes, 256);
  235. System.out.println(tag + " response " + responseCode + " " + loggerResponseString);
  236. return response;
  237. }
  238. private static String getLoggerString(final byte[] data, int maxLength) {
  239. String loggerString;
  240. if (data.length > maxLength) {
  241. byte[] shortData = new byte[maxLength];
  242. System.arraycopy(data, 0, shortData, 0, shortData.length);
  243. try {
  244. loggerString = new String(shortData, "UTF-8") + "...";
  245. } catch (UnsupportedEncodingException e) {
  246. loggerString = new String(shortData) + "...";
  247. }
  248. } else {
  249. try {
  250. loggerString = new String(data, "UTF-8");
  251. } catch (UnsupportedEncodingException e) {
  252. loggerString = new String(data);
  253. }
  254. }
  255. char[] chars = new char[loggerString.length()];
  256. loggerString.getChars(0, loggerString.length(), chars, 0);
  257. for (int i = 0; i < chars.length; i++) {
  258. char c = chars[i];
  259. if (c == '\n' || c == '\r') {
  260. chars[i] = ' ';
  261. }
  262. }
  263. return new String(chars);
  264. }
  265. private static CloseableHttpClient getHttpClient(String requestPath) {
  266. if (httpClients.containsKey(requestPath)) {
  267. return httpClients.get(requestPath);
  268. }
  269. if (poolingHttpClientConnectionManager == null) {
  270. synchronized (o) {
  271. if (poolingHttpClientConnectionManager == null) {
  272. poolingHttpClientConnectionManager = HttpClientUtils.createHttpClientConnectionManager();
  273. }
  274. }
  275. }
  276. synchronized (httpClients) {
  277. if (httpClients.containsKey(requestPath)) {
  278. return httpClients.get(requestPath);
  279. }
  280. CloseableHttpClient httpClient = HttpClientUtils.createHttpClient(poolingHttpClientConnectionManager);
  281. httpClients.put(requestPath, httpClient);
  282. return httpClient;
  283. }
  284. }
  285. private static class HttpClientUtils {
  286. // 默认连接超时
  287. private static int defaultConnectTimeout = 6000;
  288. // 默认读取超时
  289. private static int defaultReadTimeout = 30000;
  290. public static CloseableHttpClient createHttpClient(PoolingHttpClientConnectionManager connManager) {
  291. //HttpHost httpHost = new HttpHost("10.211.55.4", 8888);
  292. CloseableHttpClient httpClient = HttpClients.custom()
  293. //.setProxy(httpHost)
  294. .setConnectionManager(connManager)
  295. .disableContentCompression()
  296. .setSSLContext(getSslcontext())
  297. .setDefaultRequestConfig(getRequestConfig())
  298. .build();
  299. return httpClient;
  300. }
  301. public static PoolingHttpClientConnectionManager createHttpClientConnectionManager() {
  302. SSLConnectionSocketFactory sslConnectionSocketFactory = null;
  303. try {
  304. sslConnectionSocketFactory = new SSLConnectionSocketFactory(getSslcontext(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  305. } catch (Exception e) {
  306. throw new RuntimeException(e.getMessage(), e);
  307. }
  308. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  309. .register("https", sslConnectionSocketFactory)
  310. .register("http", new PlainConnectionSocketFactory())
  311. .build();
  312. PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  313. cm.setMaxTotal(500);
  314. cm.setDefaultMaxPerRoute(500);
  315. return cm;
  316. }
  317. private static RequestConfig getRequestConfig() {
  318. RequestConfig defaultRequestConfig = RequestConfig.custom()
  319. .setConnectionRequestTimeout(defaultConnectTimeout)
  320. .setSocketTimeout(defaultReadTimeout)
  321. .build();
  322. return defaultRequestConfig;
  323. }
  324. private static SSLContext getSslcontext() {
  325. SSLContext sslContext = null;
  326. try {
  327. sslContext = SSLContext.getInstance("TLS");
  328. TrustManager tm = new X509TrustManager() {
  329. @Override
  330. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  331. }
  332. @Override
  333. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  334. }
  335. @Override
  336. public X509Certificate[] getAcceptedIssuers() {
  337. return null;
  338. }
  339. };
  340. sslContext.init(null, new TrustManager[]{tm}, null);
  341. } catch (Exception e) {
  342. e.printStackTrace();
  343. }
  344. return sslContext;
  345. }
  346. }
  347. }