WebHookUtil.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. package jnpf.message.util;
  2. import cn.hutool.http.HttpUtil;
  3. import com.alibaba.fastjson.JSON;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.google.common.collect.Lists;
  6. import com.google.common.collect.Maps;
  7. import jnpf.util.DateUtil;
  8. import jnpf.util.StringUtil;
  9. import okhttp3.*;
  10. import org.apache.http.HttpResponse;
  11. import org.apache.http.client.config.RequestConfig;
  12. import org.apache.http.client.methods.HttpPost;
  13. import org.apache.http.entity.ContentType;
  14. import org.apache.http.entity.StringEntity;
  15. import org.apache.http.impl.client.CloseableHttpClient;
  16. import org.apache.http.impl.client.HttpClients;
  17. import org.apache.http.util.EntityUtils;
  18. import org.slf4j.Logger;
  19. import org.slf4j.LoggerFactory;
  20. import javax.crypto.Mac;
  21. import javax.crypto.spec.SecretKeySpec;
  22. import java.io.BufferedReader;
  23. import java.io.IOException;
  24. import java.io.InputStreamReader;
  25. import java.io.PrintWriter;
  26. import java.net.URL;
  27. import java.net.URLConnection;
  28. import java.net.URLEncoder;
  29. import java.nio.charset.StandardCharsets;
  30. import java.security.InvalidKeyException;
  31. import java.security.NoSuchAlgorithmException;
  32. import java.util.*;
  33. public class WebHookUtil {
  34. /**
  35. * post请求以及参数是json
  36. *
  37. * @param url
  38. * @param jsonParams
  39. * @return
  40. */
  41. public static JSONObject doPostForJson(String url, String jsonParams) {
  42. CloseableHttpClient httpClient = HttpClients.createDefault();
  43. JSONObject jsonObject = null;
  44. HttpPost httpPost = new HttpPost(url);
  45. RequestConfig requestConfig = RequestConfig.custom().
  46. setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
  47. .setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
  48. httpPost.setConfig(requestConfig);
  49. httpPost.setHeader("Content-Type", "application/json");
  50. try {
  51. httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", "utf-8")));
  52. System.out.println("request parameters" + EntityUtils.toString(httpPost.getEntity()));
  53. System.out.println("httpPost:" + httpPost);
  54. HttpResponse response = httpClient.execute(httpPost);
  55. if (response != null && response.getStatusLine().getStatusCode() == 200) {
  56. String result = EntityUtils.toString(response.getEntity());
  57. System.out.println("result:" + result);
  58. jsonObject = JSONObject.parseObject(result);
  59. return jsonObject;
  60. }
  61. } catch (Exception e) {
  62. e.printStackTrace();
  63. } finally {
  64. if (null != httpClient) {
  65. try {
  66. httpClient.close();
  67. } catch (IOException e) {
  68. e.printStackTrace();
  69. }
  70. }
  71. return jsonObject;
  72. }
  73. }
  74. /**
  75. * 基础验证
  76. * @param url webhook地址
  77. * @param msgList 消息内容
  78. */
  79. public static void sendMsgBasic(String url,List<String> msgList, String userName,String password) {
  80. //飞书机器人url 通过webhook将自定义服务的消息推送至飞书
  81. String content = userName + ":" + password;
  82. String token = "Basic " + Base64.getEncoder().encodeToString(content.getBytes(StandardCharsets.UTF_8));
  83. Map<String, Object> params = new LinkedHashMap<>();
  84. params.put("msg_type", "text");
  85. Map<String, Object> contentMap = new HashMap<>();
  86. params.put("content", contentMap);
  87. StringBuilder stringBuilder = new StringBuilder();
  88. msgList.forEach(e -> {
  89. stringBuilder.append(e + "\n");
  90. });
  91. contentMap.put("text", stringBuilder.toString());
  92. doPostForJsonObject(url, JSON.toJSONString(params),token);
  93. }
  94. /**
  95. * post请求以及参数是json
  96. *
  97. * @param url
  98. * @param jsonParams
  99. * @return
  100. */
  101. public static JSONObject doPostForJsonObject(String url, String jsonParams,String token) {
  102. CloseableHttpClient httpClient = HttpClients.createDefault();
  103. JSONObject jsonObject = null;
  104. HttpPost httpPost = new HttpPost(url);
  105. RequestConfig requestConfig = RequestConfig.custom().
  106. setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
  107. .setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
  108. httpPost.setConfig(requestConfig);
  109. httpPost.setHeader("Content-Type", "application/json");
  110. httpPost.setHeader("Authorization", token);
  111. try {
  112. httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", "utf-8")));
  113. System.out.println("request parameters" + EntityUtils.toString(httpPost.getEntity()));
  114. System.out.println("httpPost:" + httpPost);
  115. HttpResponse response = httpClient.execute(httpPost);
  116. if (response != null && response.getStatusLine().getStatusCode() == 200) {
  117. String result = EntityUtils.toString(response.getEntity());
  118. System.out.println("result:" + result);
  119. jsonObject = JSONObject.parseObject(result);
  120. return jsonObject;
  121. }
  122. } catch (Exception e) {
  123. e.printStackTrace();
  124. } finally {
  125. if (null != httpClient) {
  126. try {
  127. httpClient.close();
  128. } catch (IOException e) {
  129. e.printStackTrace();
  130. }
  131. }
  132. return jsonObject;
  133. }
  134. }
  135. /**
  136. * 把timestamp+"\n"+密钥当做签名字符串并计算签名
  137. * @param secret bearer令牌
  138. * @param timestamp 当前时间的时间戳格式
  139. * @return
  140. * @throws NoSuchAlgorithmException
  141. * @throws InvalidKeyException
  142. */
  143. private static String GenSign(String secret, Long timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
  144. //把timestamp+"\n"+密钥当做签名字符串
  145. String stringToSign = timestamp + "\n" + secret;
  146. //使用HmacSHA256算法计算签名
  147. Mac mac = Mac.getInstance("HmacSHA256");
  148. mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
  149. byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
  150. return new String(Base64.getEncoder().encode(signData));
  151. }
  152. /**
  153. * 对接飞书机器人发送消息(webhook),bearer令牌类型
  154. * @param url 飞书机器人webhook的值
  155. * @param msgList 消息内容
  156. * @param Secret bearer令牌
  157. * @throws NoSuchAlgorithmException
  158. * @throws InvalidKeyException
  159. */
  160. public static void sendMsg(String url, List<String> msgList, String Secret) throws NoSuchAlgorithmException, InvalidKeyException {
  161. //飞书机器人url 通过webhook和密钥将自定义服务的消息推送至飞书
  162. Map<String, Object> params = new LinkedHashMap<>();
  163. Long timestamp = DateUtil.getTime(DateUtil.getNowDate());
  164. String sign = GenSign(Secret,timestamp);
  165. params.put("msg_type", "text");
  166. params.put("timestamp",timestamp);
  167. params.put("sign",sign);
  168. Map<String, Object> contentMap = new HashMap<>();
  169. params.put("content", contentMap);
  170. StringBuilder stringBuilder = new StringBuilder();
  171. msgList.forEach(e -> {
  172. stringBuilder.append(e + "\n");
  173. });
  174. contentMap.put("text", stringBuilder.toString());
  175. doPostForJson(url, JSON.toJSONString(params));
  176. }
  177. /**
  178. * 对接飞书机器人发送消息(webhook),无bearer令牌
  179. * @param url 飞书机器人webhook的值
  180. * @param msgList 消息内容
  181. */
  182. public static void sendMsgNoSecret(String url,List<String> msgList) {
  183. //飞书机器人url 通过webhook将自定义服务的消息推送至飞书
  184. Map<String, Object> params = new LinkedHashMap<>();
  185. params.put("msg_type", "text");
  186. Map<String, Object> contentMap = new HashMap<>();
  187. params.put("content", contentMap);
  188. StringBuilder stringBuilder = new StringBuilder();
  189. msgList.forEach(e -> {
  190. stringBuilder.append(e + "\n");
  191. });
  192. contentMap.put("text", stringBuilder.toString());
  193. doPostForJson(url, JSON.toJSONString(params));
  194. }
  195. private static Logger logger = LoggerFactory.getLogger(WebHookUtil.class);
  196. /**
  197. * 发送POST请求,参数是Map, contentType=x-www-form-urlencoded
  198. *
  199. * @param url
  200. * @param mapParam
  201. * @return
  202. */
  203. public static String sendPostByMap(String url, Map<String, Object> mapParam) {
  204. Map<String, String> headParam = new HashMap();
  205. headParam.put("Content-type", "application/json;charset=UTF-8");
  206. return sendPost(url, mapParam, headParam);
  207. }
  208. /**
  209. * 向指定 URL 发送POST方法的请求
  210. *
  211. * @param url 发送请求的 URL
  212. * @param param 请求参数,
  213. * @return 所代表远程资源的响应结果
  214. */
  215. public static String sendPost(String url, Map<String, Object> param, Map<String, String> headParam) {
  216. PrintWriter out = null;
  217. BufferedReader in = null;
  218. String result = "";
  219. try {
  220. URL realUrl = new URL(url);
  221. // 打开和URL之间的连接
  222. URLConnection conn = realUrl.openConnection();
  223. // 设置通用的请求属性 请求头
  224. conn.setRequestProperty("accept", "*/*");
  225. conn.setRequestProperty("connection", "Keep-Alive");
  226. conn.setRequestProperty("user-agent",
  227. "Fiddler");
  228. if (headParam != null) {
  229. for (Map.Entry<String, String> entry : headParam.entrySet()) {
  230. conn.setRequestProperty(entry.getKey(), entry.getValue());
  231. }
  232. }
  233. // 发送POST请求必须设置如下两行
  234. conn.setDoOutput(true);
  235. conn.setDoInput(true);
  236. // 获取URLConnection对象对应的输出流
  237. out = new PrintWriter(conn.getOutputStream());
  238. // 发送请求参数
  239. out.print(JSON.toJSONString(param));
  240. // flush输出流的缓冲
  241. out.flush();
  242. // 定义BufferedReader输入流来读取URL的响应
  243. in = new BufferedReader(
  244. new InputStreamReader(conn.getInputStream()));
  245. String line;
  246. while ((line = in.readLine()) != null) {
  247. result += line;
  248. }
  249. } catch (Exception e) {
  250. logger.info("发送 POST 请求出现异常!" + e);
  251. e.printStackTrace();
  252. }
  253. //使用finally块来关闭输出流、输入流
  254. finally {
  255. try {
  256. if (out != null) {
  257. out.close();
  258. }
  259. if (in != null) {
  260. in.close();
  261. }
  262. } catch (IOException ex) {
  263. ex.printStackTrace();
  264. }
  265. }
  266. return result;
  267. }
  268. /**
  269. * 发送文字消息
  270. *
  271. * @param msg 需要发送的消息
  272. * @return
  273. * @throws Exception
  274. */
  275. public static String sendTextMsg(String msg){
  276. JSONObject text = new JSONObject();
  277. text.put("content", msg);
  278. JSONObject reqBody = new JSONObject();
  279. reqBody.put("msgtype", "text");
  280. reqBody.put("text", text);
  281. reqBody.put("safe", 0);
  282. return reqBody.toString();
  283. }
  284. /**
  285. * 对接企业微信机器人发送消息(webhook)
  286. * @content:要发送的消息
  287. * WECHAT_GROUP:机器人的webhook
  288. */
  289. public static JSONObject callWeChatBot(String url,String content){
  290. OkHttpClient client = new OkHttpClient()
  291. .newBuilder()
  292. .build();
  293. MediaType mediaType = MediaType.parse("application/json");
  294. content = sendTextMsg(content);
  295. RequestBody body = RequestBody.create(content,mediaType);
  296. Request request = new Request.Builder()
  297. .url(url)
  298. .method("POST", body)
  299. .addHeader("Content-Type", "application/json")
  300. .build();
  301. String result = "";
  302. try (Response response = client.newCall(request).execute()){
  303. result = response.body().string();
  304. } catch (IOException e) {
  305. e.printStackTrace();
  306. }
  307. return JSONObject.parseObject(result);
  308. }
  309. /**
  310. * 对接钉钉机器人发送消息(webhook)
  311. * @param url 钉钉上获取到的webhook的值
  312. * @param msg 发送的消息内容
  313. */
  314. public static JSONObject sendDDMessage(String url,String msg) {
  315. //钉钉的webhook
  316. //请求的JSON数据,这里用map在工具类里转成json格式
  317. Map<String, Object> json = new HashMap();
  318. Map<String, Object> text = new HashMap();
  319. json.put("msgtype", "text");
  320. text.put("content", msg);
  321. json.put("text", text);
  322. //发送post请求
  323. String response = WebHookUtil.sendPostByMap(url, json);
  324. return JSONObject.parseObject(response);
  325. }
  326. /**
  327. * 通过加签方式调用钉钉机器人发送消息给所有人
  328. */
  329. public static JSONObject sendDingDing(String url,String Secret,String content) {
  330. try {
  331. //钉钉机器人地址(配置机器人的webhook)
  332. Long timestamp = System.currentTimeMillis();
  333. String sign = GenSign(Secret,timestamp);
  334. String stringToSign = timestamp + "\n" + Secret;
  335. String dingUrl = url + "&timestamp=" + timestamp + "&sign=" + URLEncoder.encode(sign, "UTF-8");
  336. //是否通知所有人
  337. boolean isAtAll = true;
  338. //通知具体人的手机号码列表
  339. // List<String> mobileList = Lists.newArrayList();
  340. //mobileList.add("+86-159*******");
  341. //消息内容
  342. Map<String, String> contentMap = Maps.newHashMap();
  343. contentMap.put("content", content);
  344. //通知人
  345. Map<String, Object> atMap = Maps.newHashMap();
  346. //1.是否通知所有人
  347. atMap.put("isAtAll", isAtAll);
  348. //2.通知具体人的手机号码列表
  349. // atMap.put("atMobiles", mobileList);
  350. Map<String, Object> reqMap = Maps.newHashMap();
  351. reqMap.put("msgtype", "text");
  352. reqMap.put("text", contentMap);
  353. reqMap.put("at", atMap);
  354. //推送消息(http请求)
  355. String result = sendPostByMap(dingUrl, reqMap);
  356. return JSONObject.parseObject(result);
  357. }catch (Exception e){
  358. e.printStackTrace();
  359. }
  360. return null;
  361. }
  362. }