HttpUtils.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. package com.project.common.utils.http;
  2. import com.alibaba.fastjson2.JSON;
  3. import com.project.common.constant.Constants;
  4. import com.project.common.exception.ServiceException;
  5. import com.project.common.utils.StringUtils;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import javax.net.ssl.*;
  9. import java.io.*;
  10. import java.net.ConnectException;
  11. import java.net.SocketTimeoutException;
  12. import java.net.URL;
  13. import java.net.URLConnection;
  14. import java.nio.charset.StandardCharsets;
  15. import java.security.cert.X509Certificate;
  16. import java.util.Map;
  17. /**
  18. * 通用http发送方法
  19. *
  20. * @author ruoyi
  21. */
  22. public class HttpUtils {
  23. private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
  24. /**
  25. * 向指定 URL 发送GET方法的请求
  26. *
  27. * @param url 发送请求的 URL
  28. * @return 所代表远程资源的响应结果
  29. */
  30. public static String sendGet(String url) {
  31. return sendGet(url, StringUtils.EMPTY);
  32. }
  33. /**
  34. * 向指定 URL 发送GET方法的请求
  35. *
  36. * @param url 发送请求的 URL
  37. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  38. * @return 所代表远程资源的响应结果
  39. */
  40. public static String sendGet(String url, String param) {
  41. return sendGet(url, param, Constants.UTF8);
  42. }
  43. /**
  44. * 向指定 URL 发送GET方法的请求
  45. *
  46. * @param url 发送请求的 URL
  47. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  48. * @param contentType 编码类型
  49. * @return 所代表远程资源的响应结果
  50. */
  51. public static String sendGet(String url, String param, String contentType) {
  52. StringBuilder result = new StringBuilder();
  53. BufferedReader in = null;
  54. try {
  55. String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
  56. log.info("sendGet - {}", urlNameString);
  57. URL realUrl = new URL(urlNameString);
  58. URLConnection connection = realUrl.openConnection();
  59. // 设置连接超时时间为5000毫秒(5秒)
  60. connection.setConnectTimeout(5000);
  61. // 设置读取超时时间为60000毫秒(60秒)
  62. connection.setReadTimeout(60000);
  63. connection.setRequestProperty("accept", "*/*");
  64. connection.setRequestProperty("connection", "Keep-Alive");
  65. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  66. connection.connect();
  67. in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
  68. String line;
  69. while ((line = in.readLine()) != null) {
  70. result.append(line);
  71. }
  72. log.info("recv - {}", result);
  73. } catch (ConnectException e) {
  74. log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
  75. throw new ServiceException(e.getMessage());
  76. } catch (SocketTimeoutException e) {
  77. log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
  78. throw new ServiceException(e.getMessage());
  79. } catch (IOException e) {
  80. log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
  81. throw new ServiceException(e.getMessage());
  82. } catch (Exception e) {
  83. log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
  84. throw new ServiceException(e.getMessage());
  85. } finally {
  86. try {
  87. if (in != null) {
  88. in.close();
  89. }
  90. } catch (Exception ex) {
  91. log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
  92. }
  93. }
  94. return result.toString();
  95. }
  96. /**
  97. * 向指定 URL 发送GET方法的请求
  98. *
  99. * @param url 发送请求的 URL
  100. * @param fileName 保存的图片路径
  101. * @return 所代表远程资源的响应结果
  102. */
  103. public static String sendGetToSaveImg(String url, String fileName) {
  104. BufferedReader in = null;
  105. try {
  106. URL realUrl = new URL(url);
  107. URLConnection connection = realUrl.openConnection();
  108. connection.setRequestProperty("accept", "*/*");
  109. connection.setRequestProperty("connection", "Keep-Alive");
  110. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  111. connection.connect();
  112. InputStream inStream = connection.getInputStream();
  113. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  114. //创建一个Buffer字符串
  115. byte[] buffer = new byte[1024];
  116. //每次读取的字符串长度,如果为-1,代表全部读取完毕
  117. int len = 0;
  118. //使用一个输入流从buffer里把数据读取出来
  119. while ((len = inStream.read(buffer)) != -1) {
  120. //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
  121. outStream.write(buffer, 0, len);
  122. }
  123. //关闭输入流
  124. inStream.close();
  125. //得到图片的二进制数据,以二进制封装得到数据,具有通用性
  126. byte[] data = outStream.toByteArray();
  127. //new一个文件对象用来保存图片,默认保存当前工程根目录
  128. File imageFile = new File(fileName);
  129. FileOutputStream outFileStream = new FileOutputStream(imageFile);
  130. //写入数据
  131. outFileStream.write(data);
  132. //关闭输出流
  133. outFileStream.close();
  134. log.info("recv - {}", fileName);
  135. } catch (ConnectException e) {
  136. log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",fileName=" + fileName, e);
  137. } catch (SocketTimeoutException e) {
  138. log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",fileName=" + fileName, e);
  139. } catch (IOException e) {
  140. log.error("调用HttpUtils.sendGet IOException, url=" + url + ",fileName=" + fileName, e);
  141. } catch (Exception e) {
  142. log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",fileName=" + fileName, e);
  143. } finally {
  144. try {
  145. if (in != null) {
  146. in.close();
  147. }
  148. } catch (Exception ex) {
  149. log.error("调用in.close Exception, url=" + url + ",fileName=" + fileName, ex);
  150. }
  151. }
  152. return fileName;
  153. }
  154. /**
  155. * 向指定 URL 发送POST方法的请求
  156. *
  157. * @param url 发送请求的 URL
  158. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  159. * @return 所代表远程资源的响应结果
  160. */
  161. public static String sendPost(String url, String param) {
  162. PrintWriter out = null;
  163. BufferedReader in = null;
  164. StringBuilder result = new StringBuilder();
  165. try {
  166. log.info("sendPost - {}", url);
  167. URL realUrl = new URL(url);
  168. URLConnection conn = realUrl.openConnection();
  169. conn.setRequestProperty("accept", "*/*");
  170. conn.setRequestProperty("connection", "Keep-Alive");
  171. conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  172. conn.setRequestProperty("Accept-Charset", "utf-8");
  173. conn.setRequestProperty("content-type", "application/json");
  174. conn.setDoOutput(true);
  175. conn.setDoInput(true);
  176. out = new PrintWriter(conn.getOutputStream());
  177. out.print(param);
  178. out.flush();
  179. in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
  180. String line;
  181. while ((line = in.readLine()) != null) {
  182. result.append(line);
  183. }
  184. log.info("recv - {}", result);
  185. } catch (ConnectException e) {
  186. throw new ServiceException(e.getMessage());
  187. //log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
  188. } catch (SocketTimeoutException e) {
  189. log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
  190. throw new ServiceException(e.getMessage());
  191. } catch (IOException e) {
  192. log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
  193. throw new ServiceException(e.getMessage());
  194. } catch (Exception e) {
  195. log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
  196. throw new ServiceException(e.getMessage());
  197. } finally {
  198. try {
  199. if (out != null) {
  200. out.close();
  201. }
  202. if (in != null) {
  203. in.close();
  204. }
  205. } catch (IOException ex) {
  206. log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
  207. }
  208. }
  209. return result.toString();
  210. }
  211. /**
  212. * 向指定 URL 发送POST方法的请求
  213. *
  214. * @param url 发送请求的 URL
  215. * @param map 请求参数,请求参数应该是 requestBody 的形式。
  216. * @return 所代表远程资源的响应结果
  217. */
  218. public static String sendJsonPost(String url, Map<String, Object> map) {
  219. String param = JSON.toJSONString(map);
  220. PrintWriter out = null;
  221. BufferedReader in = null;
  222. StringBuilder result = new StringBuilder();
  223. try {
  224. log.info("sendPost - {}", url);
  225. URL realUrl = new URL(url);
  226. URLConnection conn = realUrl.openConnection();
  227. conn.setRequestProperty("accept", "*/*");
  228. conn.setRequestProperty("connection", "Keep-Alive");
  229. conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  230. conn.setRequestProperty("Accept-Charset", "utf-8");
  231. conn.setRequestProperty("content-type", "application/json");
  232. conn.setDoOutput(true);
  233. conn.setDoInput(true);
  234. out = new PrintWriter(conn.getOutputStream());
  235. out.print(param);
  236. out.flush();
  237. in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
  238. String line;
  239. while ((line = in.readLine()) != null) {
  240. result.append(line);
  241. }
  242. log.info("recv - {}", result);
  243. } catch (ConnectException e) {
  244. throw new ServiceException(e.getMessage());
  245. //log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
  246. } catch (SocketTimeoutException e) {
  247. log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
  248. throw new ServiceException(e.getMessage());
  249. } catch (IOException e) {
  250. log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
  251. throw new ServiceException(e.getMessage());
  252. } catch (Exception e) {
  253. log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
  254. throw new ServiceException(e.getMessage());
  255. } finally {
  256. try {
  257. if (out != null) {
  258. out.close();
  259. }
  260. if (in != null) {
  261. in.close();
  262. }
  263. } catch (IOException ex) {
  264. log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
  265. }
  266. }
  267. return result.toString();
  268. }
  269. /**
  270. * 向指定 URL 发送POST方法的请求
  271. *
  272. * @param url 发送请求的 URL
  273. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  274. * @return 所代表远程资源的响应结果
  275. */
  276. public static String sendPostToSaveFile(String url, String param, String fileName) {
  277. PrintWriter out = null;
  278. BufferedReader in = null;
  279. StringBuilder result = new StringBuilder();
  280. try {
  281. log.info("sendPost - {}", url);
  282. URL realUrl = new URL(url);
  283. URLConnection conn = realUrl.openConnection();
  284. conn.setRequestProperty("accept", "*/*");
  285. conn.setRequestProperty("connection", "Keep-Alive");
  286. conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  287. conn.setRequestProperty("Accept-Charset", "utf-8");
  288. conn.setRequestProperty("contentType", "application/json");
  289. conn.setDoOutput(true);
  290. conn.setDoInput(true);
  291. out = new PrintWriter(conn.getOutputStream());
  292. out.print(param);
  293. out.flush();
  294. // in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
  295. // String line;
  296. // while ((line = in.readLine()) != null) {
  297. // result.append(line);
  298. // }
  299. BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
  300. OutputStream os = new FileOutputStream(new File(fileName));
  301. int len;
  302. byte[] buffer = new byte[1024];
  303. while ((len = bis.read(buffer)) != -1) {
  304. os.write(buffer, 0, len);
  305. os.flush();
  306. }
  307. os.close();
  308. log.info("recv - {}", bis);
  309. } catch (ConnectException e) {
  310. log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
  311. } catch (SocketTimeoutException e) {
  312. log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
  313. } catch (IOException e) {
  314. log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
  315. } catch (Exception e) {
  316. log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
  317. } finally {
  318. try {
  319. if (out != null) {
  320. out.close();
  321. }
  322. if (in != null) {
  323. in.close();
  324. }
  325. } catch (IOException ex) {
  326. log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
  327. }
  328. }
  329. return fileName;
  330. }
  331. public static String sendSSLPost(String url, String param) {
  332. StringBuilder result = new StringBuilder();
  333. String urlNameString = url + "?" + param;
  334. try {
  335. log.info("sendSSLPost - {}", urlNameString);
  336. SSLContext sc = SSLContext.getInstance("SSL");
  337. sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
  338. URL console = new URL(urlNameString);
  339. HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
  340. conn.setRequestProperty("accept", "*/*");
  341. conn.setRequestProperty("connection", "Keep-Alive");
  342. conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  343. conn.setRequestProperty("Accept-Charset", "utf-8");
  344. conn.setRequestProperty("contentType", "application/json");
  345. conn.setDoOutput(true);
  346. conn.setDoInput(true);
  347. conn.setSSLSocketFactory(sc.getSocketFactory());
  348. conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
  349. conn.connect();
  350. InputStream is = conn.getInputStream();
  351. BufferedReader br = new BufferedReader(new InputStreamReader(is));
  352. String ret = "";
  353. while ((ret = br.readLine()) != null) {
  354. if (ret != null && !"".equals(ret.trim())) {
  355. result.append(new String(ret.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
  356. }
  357. }
  358. log.info("recv - {}", result);
  359. conn.disconnect();
  360. br.close();
  361. } catch (ConnectException e) {
  362. log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
  363. } catch (SocketTimeoutException e) {
  364. log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
  365. } catch (IOException e) {
  366. log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
  367. } catch (Exception e) {
  368. log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
  369. }
  370. return result.toString();
  371. }
  372. private static class TrustAnyTrustManager implements X509TrustManager {
  373. @Override
  374. public void checkClientTrusted(X509Certificate[] chain, String authType) {
  375. }
  376. @Override
  377. public void checkServerTrusted(X509Certificate[] chain, String authType) {
  378. }
  379. @Override
  380. public X509Certificate[] getAcceptedIssuers() {
  381. return new X509Certificate[]{};
  382. }
  383. }
  384. private static class TrustAnyHostnameVerifier implements HostnameVerifier {
  385. @Override
  386. public boolean verify(String hostname, SSLSession session) {
  387. return true;
  388. }
  389. }
  390. }