HttpUtils.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. package com.ruoyi.common.utils.http;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStream;
  7. import java.io.PrintWriter;
  8. import java.net.ConnectException;
  9. import java.net.HttpURLConnection;
  10. import java.net.SocketTimeoutException;
  11. import java.net.URL;
  12. import java.net.URLConnection;
  13. import java.nio.charset.StandardCharsets;
  14. import org.apache.commons.io.IOUtils;
  15. import java.security.cert.X509Certificate;
  16. import javax.net.ssl.HostnameVerifier;
  17. import javax.net.ssl.HttpsURLConnection;
  18. import javax.net.ssl.SSLContext;
  19. import javax.net.ssl.SSLSession;
  20. import javax.net.ssl.TrustManager;
  21. import javax.net.ssl.X509TrustManager;
  22. import org.slf4j.Logger;
  23. import org.slf4j.LoggerFactory;
  24. import com.ruoyi.common.constant.Constants;
  25. import com.ruoyi.common.utils.StringUtils;
  26. import org.springframework.http.MediaType;
  27. /**
  28. * 通用http发送方法
  29. *
  30. * @author ruoyi
  31. */
  32. public class HttpUtils
  33. {
  34. private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
  35. /**
  36. * 向指定 URL 发送GET方法的请求
  37. *
  38. * @param url 发送请求的 URL
  39. * @return 所代表远程资源的响应结果
  40. */
  41. public static String sendGet(String url)
  42. {
  43. return sendGet(url, StringUtils.EMPTY);
  44. }
  45. /**
  46. * 向指定 URL 发送GET方法的请求
  47. *
  48. * @param url 发送请求的 URL
  49. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  50. * @return 所代表远程资源的响应结果
  51. */
  52. public static String sendGet(String url, String param)
  53. {
  54. return sendGet(url, param, Constants.UTF8);
  55. }
  56. /**
  57. * 向指定 URL 发送GET方法的请求
  58. *
  59. * @param url 发送请求的 URL
  60. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  61. * @param contentType 编码类型
  62. * @return 所代表远程资源的响应结果
  63. */
  64. public static String sendGet(String url, String param, String contentType)
  65. {
  66. StringBuilder result = new StringBuilder();
  67. BufferedReader in = null;
  68. try
  69. {
  70. String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
  71. log.info("sendGet - {}", urlNameString);
  72. URL realUrl = new URL(urlNameString);
  73. URLConnection connection = realUrl.openConnection();
  74. connection.setRequestProperty("accept", "*/*");
  75. connection.setRequestProperty("connection", "Keep-Alive");
  76. connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
  77. connection.connect();
  78. in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
  79. String line;
  80. while ((line = in.readLine()) != null)
  81. {
  82. result.append(line);
  83. }
  84. log.info("recv - {}", result);
  85. }
  86. catch (ConnectException e)
  87. {
  88. log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
  89. }
  90. catch (SocketTimeoutException e)
  91. {
  92. log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
  93. }
  94. catch (IOException e)
  95. {
  96. log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
  97. }
  98. catch (Exception e)
  99. {
  100. log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
  101. }
  102. finally
  103. {
  104. try
  105. {
  106. if (in != null)
  107. {
  108. in.close();
  109. }
  110. }
  111. catch (Exception ex)
  112. {
  113. log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
  114. }
  115. }
  116. return result.toString();
  117. }
  118. /**
  119. * 向指定 URL 发送POST方法的请求
  120. *
  121. * @param url 发送请求的 URL
  122. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  123. * @return 所代表远程资源的响应结果
  124. */
  125. public static String sendPost(String url, String param)
  126. {
  127. return sendPost(url, param, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
  128. }
  129. /**
  130. * 向指定 URL 发送POST方法的请求
  131. *
  132. * @param url 发送请求的 URL
  133. * @param param 请求参数
  134. * @param contentType 内容类型
  135. * @return 所代表远程资源的响应结果
  136. */
  137. public static String sendPost(String url, String param, String contentType)
  138. {
  139. PrintWriter out = null;
  140. BufferedReader in = null;
  141. StringBuilder result = new StringBuilder();
  142. try
  143. {
  144. log.info("sendPost - {}", url);
  145. URL realUrl = new URL(url);
  146. URLConnection conn = realUrl.openConnection();
  147. conn.setRequestProperty("accept", "*/*");
  148. conn.setRequestProperty("connection", "Keep-Alive");
  149. conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
  150. conn.setRequestProperty("Accept-Charset", "utf-8");
  151. conn.setRequestProperty("Content-Type", contentType);
  152. conn.setDoOutput(true);
  153. conn.setDoInput(true);
  154. out = new PrintWriter(conn.getOutputStream());
  155. out.print(param);
  156. out.flush();
  157. in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
  158. String line;
  159. while ((line = in.readLine()) != null)
  160. {
  161. result.append(line);
  162. }
  163. log.info("recv - {}", result);
  164. }
  165. catch (ConnectException e)
  166. {
  167. log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
  168. }
  169. catch (SocketTimeoutException e)
  170. {
  171. log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
  172. }
  173. catch (IOException e)
  174. {
  175. log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
  176. }
  177. catch (Exception e)
  178. {
  179. log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
  180. }
  181. finally
  182. {
  183. try
  184. {
  185. if (out != null)
  186. {
  187. out.close();
  188. }
  189. if (in != null)
  190. {
  191. in.close();
  192. }
  193. }
  194. catch (IOException ex)
  195. {
  196. log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
  197. }
  198. }
  199. return result.toString();
  200. }
  201. public static String sendSSLPost(String url, String param)
  202. {
  203. return sendSSLPost(url, param, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
  204. }
  205. public static String sendSSLPost(String url, String param, String contentType)
  206. {
  207. StringBuilder result = new StringBuilder();
  208. String urlNameString = url + "?" + param;
  209. try
  210. {
  211. log.info("sendSSLPost - {}", urlNameString);
  212. SSLContext sc = SSLContext.getInstance("SSL");
  213. sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
  214. URL console = new URL(urlNameString);
  215. HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
  216. conn.setRequestProperty("accept", "*/*");
  217. conn.setRequestProperty("connection", "Keep-Alive");
  218. conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
  219. conn.setRequestProperty("Accept-Charset", "utf-8");
  220. conn.setRequestProperty("Content-Type", contentType);
  221. conn.setDoOutput(true);
  222. conn.setDoInput(true);
  223. conn.setSSLSocketFactory(sc.getSocketFactory());
  224. conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
  225. conn.connect();
  226. InputStream is = conn.getInputStream();
  227. BufferedReader br = new BufferedReader(new InputStreamReader(is));
  228. String ret = "";
  229. while ((ret = br.readLine()) != null)
  230. {
  231. if (ret != null && !"".equals(ret.trim()))
  232. {
  233. result.append(new String(ret.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
  234. }
  235. }
  236. log.info("recv - {}", result);
  237. conn.disconnect();
  238. br.close();
  239. }
  240. catch (ConnectException e)
  241. {
  242. log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
  243. }
  244. catch (SocketTimeoutException e)
  245. {
  246. log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
  247. }
  248. catch (IOException e)
  249. {
  250. log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
  251. }
  252. catch (Exception e)
  253. {
  254. log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
  255. }
  256. return result.toString();
  257. }
  258. private static class TrustAnyTrustManager implements X509TrustManager
  259. {
  260. @Override
  261. public void checkClientTrusted(X509Certificate[] chain, String authType)
  262. {
  263. }
  264. @Override
  265. public void checkServerTrusted(X509Certificate[] chain, String authType)
  266. {
  267. }
  268. @Override
  269. public X509Certificate[] getAcceptedIssuers()
  270. {
  271. return new X509Certificate[] {};
  272. }
  273. }
  274. private static class TrustAnyHostnameVerifier implements HostnameVerifier
  275. {
  276. @Override
  277. public boolean verify(String hostname, SSLSession session)
  278. {
  279. return true;
  280. }
  281. }
  282. /**
  283. * 向指定 URL 发送GET方法的请求,并将响应流写入到指定的输出流
  284. *
  285. * @param url 发送请求的 URL
  286. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  287. * @param outputStream 输出流,用于写入响应数据
  288. * @throws IOException IO异常
  289. */
  290. public static void sendGetStream(String url, String param, OutputStream outputStream) throws IOException
  291. {
  292. HttpURLConnection connection = null;
  293. InputStream inputStream = null;
  294. try
  295. {
  296. String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
  297. log.info("sendGetStream - {}", urlNameString);
  298. URL realUrl = new URL(urlNameString);
  299. connection = (HttpURLConnection) realUrl.openConnection();
  300. connection.setRequestMethod("GET");
  301. connection.setConnectTimeout(30000);
  302. connection.setReadTimeout(30000);
  303. connection.setRequestProperty("accept", "*/*");
  304. connection.setRequestProperty("connection", "Keep-Alive");
  305. connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
  306. connection.setDoInput(true);
  307. connection.connect();
  308. int responseCode = connection.getResponseCode();
  309. if (responseCode == HttpURLConnection.HTTP_OK)
  310. {
  311. inputStream = connection.getInputStream();
  312. IOUtils.copy(inputStream, outputStream);
  313. outputStream.flush();
  314. }
  315. else
  316. {
  317. throw new IOException("远程服务器返回错误: " + responseCode);
  318. }
  319. }
  320. catch (ConnectException e)
  321. {
  322. log.error("调用HttpUtils.sendGetStream ConnectException, url=" + url + ",param=" + param, e);
  323. throw e;
  324. }
  325. catch (SocketTimeoutException e)
  326. {
  327. log.error("调用HttpUtils.sendGetStream SocketTimeoutException, url=" + url + ",param=" + param, e);
  328. throw e;
  329. }
  330. catch (IOException e)
  331. {
  332. log.error("调用HttpUtils.sendGetStream IOException, url=" + url + ",param=" + param, e);
  333. throw e;
  334. }
  335. catch (Exception e)
  336. {
  337. log.error("调用HttpUtils.sendGetStream Exception, url=" + url + ",param=" + param, e);
  338. throw new IOException("调用远程服务器失败", e);
  339. }
  340. finally
  341. {
  342. try
  343. {
  344. if (inputStream != null)
  345. {
  346. inputStream.close();
  347. }
  348. if (connection != null)
  349. {
  350. connection.disconnect();
  351. }
  352. }
  353. catch (Exception ex)
  354. {
  355. log.error("调用sendGetStream关闭资源 Exception, url=" + url + ",param=" + param, ex);
  356. }
  357. }
  358. }
  359. }