对接钉钉机器人发送钉钉通知

发布时间:2024年01月23日
  • 实现效果
    在这里插入图片描述
  • 话不多说 直接上代码
static void sendMsg(String msg) {

        new Thread(()->{

            try {
                String content = "{\"msgtype\": \"text\",\"text\": {\"content\": \"" + msg + "\"}}";
                HttpUtil.simplePost(content, getDingUrl());
            } catch (Exception e) {
                log.error("钉钉消息发送失败",e);
            }

        }).start();
    }

private static String getDingUrl() throws Exception {
        // 获取系统时间戳
        Long timestamp = System.currentTimeMillis();
        // 拼接  钉钉加签
        String stringToSign = timestamp + "\n" + "SEC0c2c93412cff6ac2e****ac939189971c0b";
        // 使用HmacSHA256算法计算签名
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec("SEC0c2c93412cff6ac2e****ac939189971c0b".getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        // 进行Base64 encode 得到最后的sign,可以拼接进url里
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        // 钉钉机器人地址(配置机器人的webhook),为了让每次请求不同,避免钉钉拦截,加上时间戳
        return "https://oapi.dingtalk.com/robot/send?access_token=" + "&timestamp=" + timestamp + "&sign=" + sign;
    }
  • http工具类
package com.ncarzone.coserviceability.coupon;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * HttpUtil 请求
 * @author zhouyang
 */
public class HttpUtil {
	private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
	private static CloseableHttpClient httpClient;;
	private static RequestConfig requestConfig;
	private static final String ENCODING = Consts.UTF_8.name();
	private static final Map<String, Object> jsonHeaderMap = new HashMap();

	static {
		try{
			jsonHeaderMap.put("Content-Type","application/json");
			PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();

			ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();
			connManager.setDefaultConnectionConfig(connectionConfig);

			connManager.setMaxTotal(50);//最大连接数
			connManager.setDefaultMaxPerRoute(5);//路由最大连接数

			SocketConfig socketConfig = SocketConfig.custom()
					.setTcpNoDelay(true)
					.build();
			connManager.setDefaultSocketConfig(socketConfig);


			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				//信任所有
				@Override
				public boolean isTrusted(X509Certificate[] chain, String authType)
						throws CertificateException {
					return true;
				}
			}).build();

			httpClient = HttpClients.custom()
					.setConnectionManager(connManager)
					.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext))
					.build();

			requestConfig = RequestConfig.custom()
					// 获取manager中连接 超时时间 50s
					.setConnectionRequestTimeout(5000)
					// 连接服务器 超时时间  1500s
					.setConnectTimeout(150000)
					// 服务器处理 超时时间 3000s
					.setSocketTimeout(300000)
					.build();
		}catch(Exception e){
			throw new RuntimeException("创建httpClient失败", e);
		}
	}

	public static final String simpleGet(String addr) {
		return doGet(addr, null);
	}

	public static String doGet(String url) {
		HttpGet get = new HttpGet(url);
		try (CloseableHttpResponse response = httpClient.execute(get);) {
			get.setConfig(requestConfig);
			if (response.getStatusLine().getStatusCode() == 200) {//成功
				return EntityUtils.toString(response.getEntity(), ENCODING);
			}
		} catch (Exception e) {
			log.error("invoke target error", e);
		}
		return null;
	}



	public static String doGet(String url, Map<String, Object> paramMap) {
		url = appendParamsToUrl(url, paramMap);
		return doGet(url);
	}

	private static String appendParamsToUrl(String url, Map<String, Object> paramMap) {
		if (paramMap != null && !paramMap.isEmpty()) {
			StringBuilder fullUrlString = new StringBuilder(url);
			if (!StringUtils.contains(url, "?")) {
				fullUrlString.append("?");
			} else {
				fullUrlString.append("&");
			}
			for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
				fullUrlString.append(entry.getKey());
				fullUrlString.append("=");
				fullUrlString.append(entry.getValue());
				fullUrlString.append("&");
			}
			return StringUtils.removeEnd(fullUrlString.toString(), "&");
		}
		return url;
	}

	public static final String simplePost(final String body, final String url) {
		return doPost(url, body, jsonHeaderMap);
	}

	/**
	 * post请求发送
	 */
	public static String doPost(String url, String bodyString, Map<String, Object> headerMap) {
		HttpPost post = new HttpPost(url);
		StringEntity entity = new StringEntity(bodyString, ENCODING);
		post.setEntity(entity);
		if (headerMap != null && !headerMap.isEmpty()) {
			headerMap.forEach((k, v) -> post.setHeader(k, String.valueOf(v)));
		}
		post.setConfig(requestConfig);
		try (CloseableHttpResponse response = httpClient.execute(post)) {
			if (response.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(response.getEntity(), ENCODING);
			}
		} catch (Exception e) {
			log.error("invoke post error", e);
		}
		return null;
	}

	/**
	 * post请求发送
	 */
	public static String doPost2(String url, Map<String, String> bodyMap, Map<String, Object> headerMap) {
		HttpPost post = new HttpPost(url);
		if (headerMap != null && !headerMap.isEmpty()) {
			headerMap.forEach((k, v) -> post.setHeader(k, String.valueOf(v)));
		}
		Iterator<Map.Entry<String, String>> it = bodyMap.entrySet().iterator();
		List<NameValuePair> params = Lists.newArrayList();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = it.next();
			NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
			params.add(pair);
		}
		try {
			post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
		} catch (Exception e) {

		}
		post.setConfig(requestConfig);
		try (CloseableHttpResponse response = httpClient.execute(post)) {
			if (response.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(response.getEntity(), ENCODING);
			}
		} catch (Exception e) {
			log.error("invoke post error", e);
		}
		return null;
	}

	public static byte[] doPostPic(String url, String bodyString) {
		HttpPost post = new HttpPost(url);
		StringEntity entity = new StringEntity(bodyString, ENCODING);
		post.setEntity(entity);
		post.setConfig(requestConfig);
		try (CloseableHttpResponse response = httpClient.execute(post)) {
			if (response.getStatusLine().getStatusCode() == 200) {
				return IOUtils.toByteArray(response.getEntity().getContent());
			}
		} catch (Exception e) {
			log.error("invoke post error", e);
		}
		return null;
	}

	/**
	 * 根据传入的HttpPost/HttpGet发起请求
	 * @param request
	 * @return 正常返回结果字符串,200以外状态码或异常返回null
	 */
	public static final String excute(final HttpRequestBase request){
		CloseableHttpResponse httpResp = null;
        String result = "";
		try {
			request.setConfig(requestConfig);
            httpResp = httpClient.execute(request);

            if (httpResp.getStatusLine().getStatusCode() == 200) {//成功
                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
            }
            if (result.indexOf("'status':'0'") != -1) {
                result = "{" + result.replace("\n", "").replace("';'", "','") + "}";
                JSONObject resultMap = JSONObject.parseObject(result);
                if (resultMap.get("name") != null
                        && StringUtils.isNotEmpty((resultMap.get("name").toString()))) {
                    log.info("remote file : http://s00.zhangzhongpei.com/{} had override",
                            resultMap.get("name").toString());
                    log.info("end upload synonym file ...");
                }
            }
		} catch (Exception e) {
			log.error("invoke post error", e);
		} finally{
			try {
				if(httpResp != null){
					httpResp.close();
				}
			} catch (IOException e) {
				log.error("操作失败:" + e);
			}
		}
		return result;
	}

	public static String mapToStr(Map<String, String> map){
		StringBuilder sb = new StringBuilder();
		for (Map.Entry entry : map.entrySet()) {
			sb = sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
		}
		return sb.toString();
	}
}
  • 跑个main方法直接测试即可
    public static void main(String[] args) {
        sendMsg("this is test message");
    }
    
文章来源:https://blog.csdn.net/weixin_40869022/article/details/135777185
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。