旁观者悲

导航

钉钉报警工具类

添加钉钉依赖,修改token和secret即可直接用

  okHttp 请求

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class DingHttpUtil {

    @Autowired
    private static OkHttpClient mClient;
    private static String url;

    //初始化客户端
    static {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(10L, TimeUnit.SECONDS);
        builder.readTimeout(10L, TimeUnit.SECONDS);
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequestsPerHost(200);
        dispatcher.setMaxRequests(200);
        builder.dispatcher(dispatcher);
        mClient = builder.build();
        try {
            url = getSign();
        } catch (Exception e) {
            log.error("获取签名失败!");
            e.printStackTrace();
        }
    }

    /**
     * 通用 POST 请求方法  依赖 OKhttp3
     * @param message 所要发送的消息
     * @return 发送状态回执
     */
    public static String postWithJson(String message) {
        JSONObject jsonObject = new JSONObject();
        //固定参数
        jsonObject.put("msgtype", "text");
        JSONObject content = new JSONObject();
        //此处message是你想要发送到钉钉的信息
        content.put("content", message);
        jsonObject.put("text", content);
        RequestBody body = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString());
        Request request = new Request.Builder().url(url).post(body).build();
        try {
            Response response = mClient.newCall(request).execute();
            if (response.body() != null) {
                return response.body().string();
            }
        } catch (IOException e) {
            log.error("消息发送失败!");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取签名
     * @return 返回签名
     */
    private static String getSign() throws Exception {
        //表 缓存  @cache
        long timestamp = System.currentTimeMillis();
        String baseUrl = "https://oapi.dingtalk.com/robot/send?access_token=";
        String token = "啦啦啦啦啦";
        String secret = "超超帅过金城武";
       // System.out.println(dIngDingCheck);
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return baseUrl + token + "&timestamp=" + timestamp + "&sign=" +
                URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
    }
}

  RestTemplate请求

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.link.monitor.vo.DingModel;
import com.link.monitor.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Objects;

/**
 * Created by IntelliJ IDEA.
 * User: 人余阿巴阿巴
 * Date: 2021/7/8 15:52
 * restemplate 请求
 *
 */

@Slf4j
@Component
public class DingRestTemplateUtil {

    @Autowired
    private RestTemplate restTemplate;
    /**
     * 发送消息
     * @param content
     */
    public String sendMessage(String content){
        DingModel dingModel = new DingModel();
        dingModel.setMsgtype("text");
        HashMap<String, Object> map = new HashMap<>();
        map.put("content",content);
        dingModel.setText(map);
        ObjectMapper mapper = new ObjectMapper();
        String dingModelJson = null;
        try {
         dingModelJson = mapper.writeValueAsString(dingModel);
        //设置请求头Header
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        //设置访问的对象
            HttpEntity<String> httpEntity = new HttpEntity<>(dingModelJson, httpHeaders);
            ResponseEntity<ResultVO> response=null;
            String url="";
            try{
                 url=getSign() ;
            } catch (Exception e){
                e.printStackTrace();
                log.error("获取钉钉签名失败!!!");
            }
            //发送一个restTemplate:post请求
            response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, ResultVO.class);
            if (Objects.isNull(response)) {
                return response.getBody().toString();
            }
        } catch(NullPointerException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return  null;
    }

    private static String getSign() throws Exception {
        //baseUrl token secret 做成配置文件
        String baseUrl = "https://oapi.dingtalk.com/robot/send?access_token=";
        String token = "lalalalalalal";
        String secret = "超哥帅过金城武";
        long timestamp = System.currentTimeMillis();
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return baseUrl + token + "&timestamp=" + timestamp + "&sign=" +
                URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
    }

}

 

posted on 2021-11-02 17:59  旁观者悲  阅读(90)  评论(0)    收藏  举报