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

  • 实现效果
    在这里插入图片描述
  • 话不多说 直接上代码
static void sendMsg(String msg) {

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

        



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工具类

import org.apache.http.Consts;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
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 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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值