HttpUtils.java 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. package com.mes.util;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import java.io.*;
  5. import java.net.HttpURLConnection;
  6. import java.net.URISyntaxException;
  7. import java.net.URL;
  8. import java.nio.charset.StandardCharsets;
  9. public class HttpUtils {
  10. public static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
  11. /**
  12. * HTTP请求,正确报文解析,并保存数据到生产记录数据
  13. * @return
  14. * @throws URISyntaxException
  15. */
  16. //http post请求
  17. public static String sendRequest(String urlParam) {
  18. String requestType = "POST";
  19. //根据接收内容返回数据结果
  20. String ret = "";
  21. log.info("http请求路径: {}", urlParam);
  22. HttpURLConnection con = null;
  23. BufferedReader buffer = null;
  24. StringBuffer resultBuffer = null;
  25. try {
  26. URL url = new URL(urlParam);
  27. //得到连接对象
  28. con = (HttpURLConnection) url.openConnection();
  29. //设置请求类型
  30. con.setRequestMethod(requestType);
  31. //设置请求需要返回的数据类型和字符集类型
  32. con.setRequestProperty("Content-Type", "application/json;charset=GBK");
  33. //允许写出
  34. con.setDoOutput(true);
  35. //允许读入
  36. con.setDoInput(true);
  37. //不使用缓存
  38. con.setUseCaches(false);
  39. //得到响应码
  40. int responseCode = con.getResponseCode();
  41. if(responseCode == HttpURLConnection.HTTP_OK){
  42. //得到响应流
  43. InputStream inputStream = con.getInputStream();
  44. //将响应流转换成字符串
  45. resultBuffer = new StringBuffer();
  46. String line;
  47. buffer = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
  48. while ((line = buffer.readLine()) != null) {
  49. resultBuffer.append(line);
  50. }
  51. log.info("http响应结果: {}", resultBuffer);
  52. ret = resultBuffer.toString();
  53. }else {
  54. //ret = String.valueOf(responseCode);
  55. ret = "false";
  56. }
  57. con.disconnect();
  58. }catch(Exception e) {
  59. ret = "false";
  60. }
  61. return ret;
  62. }
  63. public static String sendPostRequest(String urlParam, String params) {
  64. String requestType = "POST";
  65. //根据接收内容返回数据结果
  66. String ret = "";
  67. log.info("http请求路径: {}", urlParam);
  68. HttpURLConnection con = null;
  69. BufferedReader buffer = null;
  70. StringBuffer resultBuffer = null;
  71. try {
  72. URL url = new URL(urlParam);
  73. //得到连接对象
  74. con = (HttpURLConnection) url.openConnection();
  75. //设置请求类型
  76. con.setRequestMethod(requestType);
  77. //设置请求需要返回的数据类型和字符集类型
  78. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=GBK");
  79. //允许写出
  80. con.setDoOutput(true);
  81. //允许读入
  82. con.setDoInput(true);
  83. //不使用缓存
  84. con.setUseCaches(false);
  85. // 获取URLConnection对象对应的输出流
  86. OutputStreamWriter out = new OutputStreamWriter( con.getOutputStream(),"UTF-8");// utf-8编码
  87. // 发送请求参数
  88. out.write(params);
  89. //得到响应码
  90. int responseCode = con.getResponseCode();
  91. if(responseCode == HttpURLConnection.HTTP_OK){
  92. //得到响应流
  93. InputStream inputStream = con.getInputStream();
  94. //将响应流转换成字符串
  95. resultBuffer = new StringBuffer();
  96. String line;
  97. buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
  98. while ((line = buffer.readLine()) != null) {
  99. resultBuffer.append(line);
  100. }
  101. log.info("http响应结果: {}", resultBuffer);
  102. ret = resultBuffer.toString();
  103. }else {
  104. //ret = String.valueOf(responseCode);
  105. ret = "false";
  106. }
  107. con.disconnect();
  108. }catch(Exception e) {
  109. ret = "false";
  110. }
  111. return ret;
  112. }
  113. public static String sendPostRequestJson(String apiUrl, String jsonData) throws IOException {
  114. URL url = new URL(apiUrl);
  115. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  116. conn.setRequestMethod("POST");
  117. conn.setRequestProperty("Content-Type", "application/json");
  118. conn.setDoOutput(true);
  119. // 发送请求数据
  120. try (OutputStream os = conn.getOutputStream()) {
  121. byte[] input = jsonData.getBytes("utf-8");
  122. os.write(input, 0, input.length);
  123. }
  124. // 获取响应数据
  125. StringBuilder response = new StringBuilder();
  126. int responseCode = conn.getResponseCode();
  127. // System.out.println("Sending POST request to URL: " + apiUrl);
  128. // System.out.println("Post parameters: " + jsonData);
  129. // System.out.println("Response Code: " + responseCode);
  130. try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
  131. String responseLine;
  132. while ((responseLine = br.readLine()) != null) {
  133. response.append(responseLine.trim());
  134. }
  135. }
  136. conn.disconnect();
  137. return response.toString();
  138. }
  139. /**
  140. * 发送 JSON 格式的 POST 请求
  141. *
  142. * @param urlString 目标 URL
  143. * @param jsonInput JSON 请求体
  144. * @param timeoutMs 连接和读取超时时间(毫秒)
  145. * @return 响应内容(JSON 字符串),失败时返回 null
  146. */
  147. public static String sendJsonPost(String urlString, String jsonInput, int timeoutMs) {
  148. HttpURLConnection conn = null;
  149. try {
  150. // 1. 创建连接
  151. URL url = new URL(urlString);
  152. conn = (HttpURLConnection) url.openConnection();
  153. // 2. 配置请求参数
  154. conn.setRequestMethod("POST");
  155. conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
  156. conn.setRequestProperty("Accept", "application/json");
  157. conn.setConnectTimeout(timeoutMs);
  158. conn.setReadTimeout(timeoutMs);
  159. conn.setDoOutput(true); // 允许写入请求体
  160. // 3. 发送 JSON 数据
  161. try (OutputStream os = conn.getOutputStream()) {
  162. byte[] input = jsonInput.getBytes(StandardCharsets.UTF_8);
  163. os.write(input, 0, input.length);
  164. }
  165. // 4. 处理响应
  166. int status = conn.getResponseCode();
  167. if (status >= 200 && status < 300) {
  168. // 读取成功响应流
  169. try (InputStream is = conn.getInputStream();
  170. BufferedReader br = new BufferedReader(
  171. new InputStreamReader(is, StandardCharsets.UTF_8))) {
  172. StringBuilder response = new StringBuilder();
  173. String line;
  174. while ((line = br.readLine()) != null) {
  175. response.append(line);
  176. }
  177. return response.toString();
  178. }
  179. } else {
  180. // 读取错误流(部分服务器将错误信息放在错误流中)
  181. try (InputStream es = conn.getErrorStream();
  182. BufferedReader br = new BufferedReader(
  183. new InputStreamReader(es, StandardCharsets.UTF_8))) {
  184. StringBuilder errorResponse = new StringBuilder();
  185. String line;
  186. while ((line = br.readLine()) != null) {
  187. errorResponse.append(line);
  188. }
  189. log.error("HTTP Error {}: {}", status, errorResponse.toString());
  190. }
  191. return null;
  192. }
  193. } catch (Exception e) {
  194. log.error("http请求失败", e);
  195. return null;
  196. } finally {
  197. if (conn != null) {
  198. conn.disconnect(); // 关闭连接
  199. }
  200. }
  201. }
  202. /**
  203. * 发送 JSON 格式的 POST 请求
  204. *
  205. * @param urlString 目标 URL
  206. * @param jsonInput JSON 请求体
  207. * @return 响应内容(JSON 字符串),失败时返回 null
  208. */
  209. public static String sendJsonPost(String urlString, String jsonInput) {
  210. return sendJsonPost(urlString, jsonInput, 5000);
  211. }
  212. }