0


一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码)

🧑‍💻作者名称:DaenCode
🎤作者简介:啥技术都喜欢捣鼓捣鼓,喜欢分享技术、经验、生活。
😎人生感悟:尝尽人生百味,方知世间冷暖。


在这里插入图片描述


文章目录

前置介绍

Avue

基于vue和element-ui的快速开发框架 

。它的核心是数据驱动UI的思想,让我们从繁琐的crud开发中解脱出来,它的写法类似easyUI,但是写起来比easyui更容易,因为它是基础数据双向绑定以及其他vue的特性。同时不知局限于crud,它还有我们经常用的一些组件例如,表单,数据展示卡,人物展示卡等等组件。

一.官网参照

云MAS业务平台_中国移动
在这里插入图片描述

二.实现方式

基于HTTPS方式云MAS平台

三.使用文档

可以在云MAS官网进行下载,下方文档存放在了我的语雀笔记中。下载时注意下载HTTPS文档,内含接口使用规范。

在这里插入图片描述

HTTPS短信接口文档.docx

四.代码实现

4.1.接口对接代码

4.1.1.SMSHttpClient.java—接口调用

此类为对接云MAS平台接口的类。

importcom.alibaba.fastjson.JSON;importorg.apache.commons.codec.binary.Base64;importorg.springframework.util.DigestUtils;importjavax.net.ssl.*;importjava.io.*;importjava.net.URL;importjava.security.cert.CertificateException;importjava.security.cert.X509Certificate;publicclassSMSHttpClient{privatestaticString apId="";//用户名privatestaticString secretKey="";//密码privatestaticString ecName ="";//集团名称   接口联调账号  zsywzprivatestaticString sign ="";//网关签名编码privatestaticString addSerial ="106509773";//拓展码 填空privatestaticString templateid ="";//模板IDpublicstaticString msg ="123456";publicstaticString url ="https://****:28888/sms/tmpsubmit";//请求urlpublicstaticintsendMsg(String mobiles,String content)throwsUnsupportedEncodingException{SendReq sendReq =newSendReq();String[] params ={"content","test","test2"};
        sendReq.setEcName(ecName);
        sendReq.setApId(apId);
        sendReq.setSecretKey(secretKey);
        sendReq.setMobiles(mobiles);
        sendReq.setParams(JSON.toJSONString(params));
        sendReq.setSign(sign);
        sendReq.setAddSerial(addSerial);
        sendReq.setTemplateId(templateid);StringBuffer stringBuffer =newStringBuffer();
        stringBuffer.append(sendReq.getEcName());
        stringBuffer.append(sendReq.getApId());
        stringBuffer.append(sendReq.getSecretKey());
        stringBuffer.append(sendReq.getTemplateId());
        stringBuffer.append(sendReq.getMobiles());
        stringBuffer.append(sendReq.getParams());
        stringBuffer.append(sendReq.getSign());
        stringBuffer.append(sendReq.getAddSerial());System.out.println(stringBuffer.toString());
        sendReq.setMac(DigestUtils.md5DigestAsHex(stringBuffer.toString().getBytes("UTF-8")).toLowerCase());System.out.println(sendReq.getMac());String reqText =JSONUtils.obj2json(sendReq);System.out.println("发送短信参数:"+reqText);String encode =Base64.encodeBase64String(reqText.getBytes("UTF-8"));System.out.println("发送短信base64:"+encode);//System.out.println(encode);String resStr =sendPost(url,encode);System.out.println("发送短信结果:"+resStr);System.out.println(newString(Base64.decodeBase64(encode)));SendRes sendRes =JSONUtils.json2pojo(resStr,SendRes.class);if(sendRes.isSuccess()&&!"".equals(sendRes.getMsgGroup())&&"success".equals(sendRes.getRspcod())){return1;}else{return0;}}/**
* main方法测试发送短信,返回1表示成功,0表示失败
*/publicstaticvoidmain(String[] args)throwsUnsupportedEncodingException{int result =sendMsg("手机号",msg);System.out.println(result);//        System.out.println( Md5Util.MD5(Hex.encodeHexString("demo0123qwe38516fabae004eddbfa3ace1d419469613800138000[\"abcde\"]4sEuJxDpC".getBytes(StandardCharsets.UTF_8))));}/**
* 向指定 URL 发送POST方法的请求
*
* @param url
*            发送请求的 URL
* @param param
*            请求参数
* @return 所代表远程资源的响应结果
*/privatestaticStringsendPost(String url,String param){OutputStreamWriter out =null;BufferedReader in =null;String result ="";try{URL realUrl =newURL(url);trustAllHosts();HttpsURLConnection conn =(HttpsURLConnection) realUrl.openConnection();
    conn.setHostnameVerifier(DO_NOT_VERIFY);
    conn.setRequestProperty("accept","*/*");
    conn.setRequestProperty("contentType","utf-8");
    conn.setRequestProperty("connection","Keep-Alive");
    conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
    conn.setDoOutput(true);
    conn.setDoInput(true);

    out =newOutputStreamWriter(conn.getOutputStream());
    out.write(param);
    out.flush();

    in =newBufferedReader(newInputStreamReader(conn.getInputStream()));String line;while((line = in.readLine())!=null){
    result +="\n"+ line;}}catch(Exception e){
    e.printStackTrace();}finally{try{if(out !=null){
    out.close();}if(in !=null){
    in.close();}}catch(IOException ex){
    ex.printStackTrace();}}return result;}/**
    * 不检查任何证书
    */privatestaticvoidtrustAllHosts(){finalStringTAG="trustAllHosts";// 创建信任管理器TrustManager[] trustAllCerts =newTrustManager[]{newX509TrustManager(){publicjava.security.cert.X509Certificate[]getAcceptedIssuers(){returnnewjava.security.cert.X509Certificate[]{};}publicvoidcheckClientTrusted(X509Certificate[] chain,String authType)throwsCertificateException{//                Log.i(TAG, "checkClientTrusted");}publicvoidcheckServerTrusted(X509Certificate[] chain,String authType)throwsCertificateException{//                Log.i(TAG, "checkServerTrusted");}}};// Install the all-trusting trust managertry{SSLContext sc =SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts,newjava.security.SecureRandom());HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());}catch(Exception e){
    e.printStackTrace();}}finalstaticHostnameVerifierDO_NOT_VERIFY=newHostnameVerifier(){publicbooleanverify(String hostname,SSLSession session){returntrue;}//将所有验证的结果都设为true};}

4.1.2.JSONUtils—JSON工具

此类为JSON处理类

importcom.fasterxml.jackson.core.JsonParseException;importcom.fasterxml.jackson.core.JsonProcessingException;importcom.fasterxml.jackson.core.type.TypeReference;importcom.fasterxml.jackson.databind.JsonMappingException;importcom.fasterxml.jackson.databind.ObjectMapper;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importjava.io.IOException;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;/**
 * @author daencode
 * @description  json工具
 */publicclassJSONUtils{privatefinalstaticObjectMapper objectMapper =newObjectMapper();privatestaticLogger log =LoggerFactory.getLogger(JSONUtils.class);privateJSONUtils(){}publicstaticObjectMappergetInstance(){return objectMapper;}/**
     * javaBean,list,array convert to json string
     */publicstaticStringobj2json(Object obj){try{return objectMapper.writeValueAsString(obj);}catch(JsonProcessingException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}returnnull;}/**
     * javaBean,list,array convert to json string
     */publicstaticStringobj2jsonInoreString(Object obj){try{return objectMapper.writeValueAsString(obj);}catch(JsonProcessingException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}returnnull;}/**
     * json string convert to javaBean
     */publicstatic<T>Tjson2pojo(String jsonStr,Class<T> clazz){try{return objectMapper.readValue(jsonStr, clazz);}catch(JsonParseException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}catch(JsonMappingException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}catch(IOException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}returnnull;}/**
     * json string convert to map
     */publicstatic<T>Map<String,Object>json2map(String jsonStr){try{return objectMapper.readValue(jsonStr,Map.class);}catch(JsonParseException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}catch(JsonMappingException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}catch(IOException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}returnnull;}/**
     * json string convert to map with javaBean
     */publicstatic<T>Map<String,T>json2map(String jsonStr,Class<T> clazz){Map<String,Map<String,Object>> map =null;try{
            map =(Map<String,Map<String,Object>>) objectMapper.readValue(jsonStr,newTypeReference<Map<String,T>>(){});}catch(JsonParseException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}catch(JsonMappingException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}catch(IOException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}Map<String,T> result =newHashMap<String,T>();for(Map.Entry<String,Map<String,Object>> entry : map.entrySet()){
            result.put(entry.getKey(),map2pojo(entry.getValue(), clazz));}return result;}/**
     * json array string convert to list with javaBean
     */publicstatic<T>List<T>json2list(String jsonArrayStr,Class<T> clazz){List<Map<String,Object>> list =null;try{
            list =(List<Map<String,Object>>) objectMapper.readValue(jsonArrayStr,newTypeReference<List<T>>(){});}catch(JsonParseException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}catch(JsonMappingException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}catch(IOException e){// TODO Auto-generated catch block
            log.error(e.getMessage());}List<T> result =newArrayList<T>();for(Map<String,Object> map : list){
            result.add(map2pojo(map, clazz));}return result;}/**
     * map convert to javaBean
     */publicstatic<T>Tmap2pojo(Map map,Class<T> clazz){return objectMapper.convertValue(map, clazz);}}

4.1.3.SendReq.java—请求实体

此类为发送短信的请求实体。

/**
 * 发送短信请求实体
 */publicclassSendReq{privateString ecName;//集团客户名称privateString apId;//用户名privateString secretKey;//密码privateString mobiles;//手机号码逗号分隔。(如“18137282928,18137282922,18137282923”)//    private String content;//发送短信内容privateString params;//发送短信内容privateString sign;//网关签名编码,必填,签名编码在中国移动集团开通帐号后分配,可以在云MAS网页端管理子系统-SMS接口管理功能中下载。privateString addSerial;//扩展码,根据向移动公司申请的通道填写,如果申请的精确匹配通道,则填写空字符串(""),否则添加移动公司允许的扩展码。privateString mac;//API输入参数签名结果,签名算法:将ecName,apId,secretKey,mobiles,content ,sign,addSerial按照顺序拼接,然后通过md5(32位小写)计算后得出的值。/**
     * 模板id
     */privateString templateId;publicStringgetEcName(){return ecName;}publicvoidsetEcName(String ecName){this.ecName = ecName;}publicStringgetApId(){return apId;}publicvoidsetApId(String apId){this.apId = apId;}publicStringgetSecretKey(){return secretKey;}publicvoidsetSecretKey(String secretKey){this.secretKey = secretKey;}publicStringgetMobiles(){return mobiles;}publicvoidsetMobiles(String mobiles){this.mobiles = mobiles;}//    public String getContent() {//        return content;//    }////    public void setContent(String content) {//        this.content = content;//    }publicStringgetSign(){return sign;}publicvoidsetSign(String sign){this.sign = sign;}publicStringgetAddSerial(){return addSerial;}publicvoidsetAddSerial(String addSerial){this.addSerial = addSerial;}publicStringgetMac(){return mac;}publicvoidsetMac(String mac){this.mac = mac;}publicStringgetTemplateId(){return templateId;}publicvoidsetTemplateId(String templateId){this.templateId = templateId;}publicStringgetParams(){return params;}publicvoidsetParams(String params){this.params = params;}}

4.1.4.SendRes.java—响应实体

此类为发送短信的响应实体。

/**
 * 发送短信响应实体
 */publicclassSendRes{privateString rspcod;//响应码privateString msgGroup;//消息批次号,由云MAS平台生成,用于验证短信提交报告和状态报告的一致性(取值msgGroup)注:如果数据验证不通过msgGroup为空privateboolean success;publicStringgetRspcod(){return rspcod;}publicvoidsetRspcod(String rspcod){this.rspcod = rspcod;}publicStringgetMsgGroup(){return msgGroup;}publicvoidsetMsgGroup(String msgGroup){this.msgGroup = msgGroup;}publicbooleanisSuccess(){return success;}publicvoidsetSuccess(boolean success){this.success = success;}}

4.2.功能实现代码

此JS文件为Avue框架中封装的统一JS文件,在此文件中存放统一业务的前端接口。

4.2.1.封装统一接口js文件

export const noteCompany = (itemType) => {
  return request({
  url: '接口地址',
  method: 'post',
  params: {
  itemType,
  }
  })
  }

4.2.2.功能页面文件

此文件为页面文件中功能按钮部分代码(触发发送短信的功能按钮)

//按钮
  <el-button :type="type"
    icon="el-icon-check" 
    :size="size" 
    @click.native="note(row)">短信通知
    </el-button>
      //方法,根据类型匹配查出相应接收短信的人员
      note(row){
        noteCompany(row.itemType).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message:"成功发送"
          });
        }
        );
      },

4.2.3.Controller层接口

下方为后端代码中Controller层触发短信功能的代码。

/**
* 短信通知
*/@PostMapping("/noteCompany")@ApiOperationSupport(order =6)@ApiOperation(value ="短信通知", notes ="传入project")publicRnoteCompany(String itemType)throwsUnsupportedEncodingException{//查询条件List<String> companyIds=projectService.getCompanyByItem(itemType);for(int i=0;i<companyIds.size();i++){String companyId="";
        companyId=companyIds.get(i);String mobile=projectService.getMobile(companyId);SMSHttpClient.sendMsg(mobile, msg);}returnR.success("成功发送"+companyIds.size()+"信息");}

写在最后

此文到此就结束了。最后感谢大家对于本文的阅读,实现过程中如有疑问,请在评论区留言,谢谢大家。
请添加图片描述

标签: spring boot 后端 Avue

本文转载自: https://blog.csdn.net/2302_79094329/article/details/131949483
版权归原作者 DaenCode 所有, 如有侵权,请联系我们删除。

“一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码)”的评论:

还没有评论