HttpUtil.java 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. package com.dgtly.system.util;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.serializer.SerializerFeature;
  4. import org.apache.commons.lang3.StringUtils;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.http.*;
  8. import org.springframework.http.client.SimpleClientHttpRequestFactory;
  9. import org.springframework.web.client.RestTemplate;
  10. import java.util.Arrays;
  11. import java.util.List;
  12. import java.util.Map;
  13. import java.util.stream.Collectors;
  14. /**
  15. * @Author: csz
  16. * @Date: 2020/7/15 16:39
  17. * @Modified: 2026/05/09 使用Spring RestTemplate替代OkHttp,解决NoClassDefFoundError问题
  18. */
  19. public class HttpUtil {
  20. private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
  21. private static RestTemplate restTemplate;
  22. static {
  23. SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
  24. factory.setConnectTimeout(30000); // 连接超时30秒
  25. factory.setReadTimeout(30000); // 读取超时30秒
  26. restTemplate = new RestTemplate(factory);
  27. }
  28. public static String executePostBodyJsonParamList(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
  29. List<Map<String, String>> maps = Arrays.asList(params);
  30. return executePostBodyJsonParam(url, headers, maps);
  31. }
  32. public static <T> String executePostBodyJsonParam(String url, Map<String, String> headers, T params) throws Exception {
  33. HttpHeaders httpHeaders = new HttpHeaders();
  34. if (headers != null && headers.size() > 0) {
  35. for (Map.Entry<String, String> entry : headers.entrySet()) {
  36. httpHeaders.add(entry.getKey(), entry.getValue());
  37. }
  38. }
  39. httpHeaders.setContentType(MediaType.APPLICATION_JSON);
  40. String jsonBody = JSON.toJSONString(params, SerializerFeature.WriteMapNullValue);
  41. HttpEntity<String> entity = new HttpEntity<>(jsonBody, httpHeaders);
  42. log.info("ESB请求 url = [{}], headers = [{}], params = [{}]", url, JSON.toJSONString(headers), jsonBody);
  43. ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
  44. String body = response.getBody();
  45. log.info("ESB响应 returnString = [{}]", body);
  46. return body;
  47. }
  48. public static <T> String executePostBodyJsonParamRetry(String url, Map<String, String> headers, T params) throws Exception {
  49. // 简单重试逻辑:重试3次
  50. int maxRetries = 3;
  51. Exception lastException = null;
  52. for (int i = 0; i < maxRetries; i++) {
  53. try {
  54. log.info("ESB重发次数 headers = [{}], params = [{}], count = [{}]", headers, params, i + 1);
  55. return executePostBodyJsonParam(url, headers, params);
  56. } catch (Exception e) {
  57. lastException = e;
  58. log.warn("ESB请求失败,第{}次重试", i + 1, e);
  59. if (i < maxRetries - 1) {
  60. Thread.sleep(1000); // 重试间隔1秒
  61. }
  62. }
  63. }
  64. throw new Exception("ESB请求失败,已重试" + maxRetries + "次", lastException);
  65. }
  66. public static String executePostFormParam(String url, Map<String, String> headers, Map<String, String> params) {
  67. HttpHeaders httpHeaders = new HttpHeaders();
  68. if (headers != null && headers.size() > 0) {
  69. for (Map.Entry<String, String> entry : headers.entrySet()) {
  70. httpHeaders.add(entry.getKey(), entry.getValue());
  71. }
  72. }
  73. httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
  74. // 构建form参数
  75. String formBody = params.entrySet().stream()
  76. .map(entry -> entry.getKey() + "=" + entry.getValue())
  77. .collect(Collectors.joining("&"));
  78. HttpEntity<String> entity = new HttpEntity<>(formBody, httpHeaders);
  79. String returnString = null;
  80. try {
  81. ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
  82. returnString = response.getBody();
  83. log.info("onResponse is {}", returnString);
  84. } catch (Exception e) {
  85. log.error("[{}] request error , heads is [{}], params is [{}]", url, JSON.toJSONString(headers), JSON.toJSONString(params), e);
  86. }
  87. return returnString;
  88. }
  89. public static String executePostJsonParam(String url, Map<String, String> headers, Map<String, String> params) {
  90. HttpHeaders httpHeaders = new HttpHeaders();
  91. if (headers != null && headers.size() > 0) {
  92. for (Map.Entry<String, String> entry : headers.entrySet()) {
  93. httpHeaders.add(entry.getKey(), entry.getValue());
  94. }
  95. }
  96. httpHeaders.setContentType(MediaType.APPLICATION_JSON);
  97. String paramJson = JSON.toJSONString(params, SerializerFeature.WriteMapNullValue);
  98. HttpEntity<String> entity = new HttpEntity<>(paramJson, httpHeaders);
  99. String returnString = null;
  100. try {
  101. ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
  102. returnString = response.getBody();
  103. log.info("onResponse is {}", returnString);
  104. } catch (Exception e) {
  105. log.error("[{}] request error , heads is [{}], params is [{}]", url, JSON.toJSONString(headers), JSON.toJSONString(params), e);
  106. }
  107. return returnString;
  108. }
  109. /**
  110. * @description: get方法
  111. * @param: [url, headers, params]
  112. * @return: java.lang.String
  113. * @author: njs
  114. * @date: 2025/6/17 13:26
  115. */
  116. public static String executeGet(String url, Map<String, String> headers, Map<String, String> params) {
  117. // 拼接GET参数
  118. if (params != null && params.size() > 0) {
  119. List<String> noticeParams = params.entrySet().stream()
  120. .map(entry -> entry.getKey() + "=" + entry.getValue())
  121. .collect(Collectors.toList());
  122. url = url + "?" + StringUtils.join(noticeParams, "&");
  123. }
  124. log.info("url is [{}]", url);
  125. HttpHeaders httpHeaders = new HttpHeaders();
  126. if (headers != null && headers.size() > 0) {
  127. for (Map.Entry<String, String> entry : headers.entrySet()) {
  128. httpHeaders.add(entry.getKey(), entry.getValue());
  129. }
  130. }
  131. HttpEntity<String> entity = new HttpEntity<>("", httpHeaders);
  132. String returnString = null;
  133. try {
  134. ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
  135. returnString = response.getBody();
  136. log.info("onResponse is {}", returnString);
  137. } catch (Exception e) {
  138. log.warn("request is error, url =[{}]", url, e);
  139. }
  140. return returnString;
  141. }
  142. }