- 实现效果

- 话不多说 直接上代码
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=" + "×tamp=" + timestamp + "&sign=" + sign;}
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() {//信任所有@Overridepublic 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;}
}