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

这篇具有很好参考价值的文章主要介绍了一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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


一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码),SpringBoot实战,spring boot,后端,Avue,vue


前置介绍

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

一.官网参照

云MAS业务平台_中国移动
一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码),SpringBoot实战,spring boot,后端,Avue,vue

二.实现方式

基于HTTPS方式云MAS平台

三.使用文档

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

一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码),SpringBoot实战,spring boot,后端,Avue,vue

HTTPS短信接口文档.docx

四.代码实现

4.1.接口对接代码

4.1.1.SMSHttpClient.java—接口调用

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

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.DigestUtils;
import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class SMSHttpClient {

    private static String apId="";//用户名
    private static String secretKey="";//密码
    private static String ecName = "";//集团名称   接口联调账号  zsywz
    private static String sign = "";//网关签名编码
    private static String addSerial = "106509773";//拓展码 填空
    private static String templateid = "";//模板ID
    public static String msg = "123456";
    public static String url = "https://****:28888/sms/tmpsubmit";//请求url
    public static int sendMsg(String mobiles,String content) throws UnsupportedEncodingException {
        SendReq sendReq = new SendReq();
        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 = new StringBuffer();
        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(new  String(Base64.decodeBase64(encode)));
        SendRes sendRes = JSONUtils.json2pojo(resStr,SendRes.class);
        if(sendRes.isSuccess() && !"".equals(sendRes.getMsgGroup()) && "success".equals(sendRes.getRspcod())){
            return 1;
        }else{
            return 0;
        }
    }
    /**
* main方法测试发送短信,返回1表示成功,0表示失败
*/
    public static void main(String[] args) throws UnsupportedEncodingException {
        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 所代表远程资源的响应结果
*/
    private static String sendPost(String url, String param) {
    OutputStreamWriter out = null;

    BufferedReader in = null;
    String result = "";
    try {
    URL realUrl = new URL(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 = new OutputStreamWriter(conn.getOutputStream());
    out.write(param);
    out.flush();


    in = new BufferedReader(
    new InputStreamReader(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;
    }
    /**
    * 不检查任何证书
    */
    private static void trustAllHosts() {
    final String TAG = "trustAllHosts";
    // 创建信任管理器
    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {

    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    return new java.security.cert.X509Certificate[]{};
    }

    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    //                Log.i(TAG, "checkClientTrusted");
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    //                Log.i(TAG, "checkServerTrusted");
    }
    }};

    // Install the all-trusting trust manager
    try {
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {

    public boolean verify(String hostname, SSLSession session) {
    return true;
    }	//将所有验证的结果都设为true
    };
    }

4.1.2.JSONUtils—JSON工具

此类为JSON处理类

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author daencode
 * @description  json工具
 */
public class JSONUtils {

    private final static ObjectMapper objectMapper = new ObjectMapper();
    private static Logger log = LoggerFactory.getLogger(JSONUtils.class);

    private JSONUtils() {

    }

    public static ObjectMapper getInstance() {

        return objectMapper;
    }

    /**
     * javaBean,list,array convert to json string
     */
    public static String obj2json(Object obj) {

        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * javaBean,list,array convert to json string
     */
    public static String obj2jsonInoreString(Object obj)  {

        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            log.error(e.getMessage());
        }
        return null;
    }
    /**
     * json string convert to javaBean
     */
    public static <T> T json2pojo(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());
        }
        return null;
    }

    /**
     * json string convert to map
     */
    public static <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());
        }
        return null;
    }

    /**
     * json string convert to map with javaBean
     */
    public static <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,
                    new TypeReference<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 = new HashMap<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
     */
    public static <T> List<T> json2list(String jsonArrayStr, Class<T> clazz)
    {
        List<Map<String, Object>> list = null;
        try {
            list = (List<Map<String, Object>>) objectMapper.readValue(jsonArrayStr,
                    new TypeReference<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 = new ArrayList<T>();
        for (Map<String, Object> map : list) {
            result.add(map2pojo(map, clazz));
        }
        return result;
    }

    /**
     * map convert to javaBean
     */
    public static <T> T map2pojo(Map map, Class<T> clazz) {
        return objectMapper.convertValue(map, clazz);
    }
}

4.1.3.SendReq.java—请求实体

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

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

    public void setEcName(String ecName) {
        this.ecName = ecName;
    }

    public String getApId() {
        return apId;
    }

    public void setApId(String apId) {
        this.apId = apId;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getMobiles() {
        return mobiles;
    }

    public void setMobiles(String mobiles) {
        this.mobiles = mobiles;
    }

//    public String getContent() {
//        return content;
//    }
//
//    public void setContent(String content) {
//        this.content = content;
//    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    public String getAddSerial() {
        return addSerial;
    }

    public void setAddSerial(String addSerial) {
        this.addSerial = addSerial;
    }

    public String getMac() {
        return mac;
    }

    public void setMac(String mac) {
        this.mac = mac;
    }

    public String getTemplateId() {
        return templateId;
    }

    public void setTemplateId(String templateId) {
        this.templateId = templateId;
    }

    public String getParams() {
        return params;
    }

    public void setParams(String params) {
        this.params = params;
    }
}

4.1.4.SendRes.java—响应实体

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

/**
 * 发送短信响应实体
 */
public class SendRes {
    private String rspcod;//响应码
    private String msgGroup;//消息批次号,由云MAS平台生成,用于验证短信提交报告和状态报告的一致性(取值msgGroup)注:如果数据验证不通过msgGroup为空
    private boolean success;

    public String getRspcod() {
        return rspcod;
    }

    public void setRspcod(String rspcod) {
        this.rspcod = rspcod;
    }

    public String getMsgGroup() {
        return msgGroup;
    }

    public void setMsgGroup(String msgGroup) {
        this.msgGroup = msgGroup;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(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")
    public R noteCompany(String itemType) throws UnsupportedEncodingException {
    //查询条件
    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);
    }
    return R.success("成功发送"+companyIds.size()+"信息");
}

写在最后

此文到此就结束了。最后感谢大家对于本文的阅读,实现过程中如有疑问,请在评论区留言,谢谢大家。
一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码),SpringBoot实战,spring boot,后端,Avue,vue文章来源地址https://www.toymoban.com/news/detail-653259.html

到了这里,关于一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 使用Python和Twilio通过短信通知主持视频办公时间。

     当你想到“办公时间”时,你会想到什么?也许你会想象一位教授会留出时间让学生去他们的办公室寻求建议或接受指导。或者,你可以想象一位企业领导在日历上为同事和直接下属留出空间,让他们提问或分享想法。 随着虚拟和混合环境的兴起,许多人在网上办公,视频

    2023年04月15日
    浏览(33)
  • beef-xss详细教程(一文带你学会beef) | Kali下安装beef | beef-xss反射型,储存型利用 | beef实现Cookie会话劫持 | 键盘监听 | 浏览器弹窗,重定向等

    ✅作者简介:CSDN内容合伙人、信息安全专业在校大学生🏆 🔥系列专栏 :XSS漏洞应用-Beef 📃新人博主 :欢迎点赞收藏关注,会回访! 💬舞台再大,你不上台,永远是个观众。平台再好,你不参与,永远是局外人。能力再大,你不行动,只能看别人成功!没有人会关心你付

    2024年02月02日
    浏览(34)
  • 【SpringBoot】一文带你入门SpringBoot

    ✅作者简介:热爱Java后端开发的一名学习者,大家可以跟我一起讨论各种问题喔。 🍎个人主页:Hhzzy99 🍊个人信条:坚持就是胜利! 💞当前专栏:【Spring】 🥭本文内容:SpringBoot的入门学习 前面几篇文章我们学习完了 Spring 、 SpringMVC ,以及SSM整合的案例,接下来我们将进

    2024年01月22日
    浏览(21)
  • 服务端(后端)主动通知前端的实现:WebSocket(springboot中使用WebSocket案例)

    我们都知道 http 协议只能浏览器单方面向服务器发起请求获得响应,服务器不能主动向浏览器推送消息。想要实现浏览器的主动推送有两种主流实现方式: 轮询:缺点很多,但是实现简单 websocket:在浏览器和服务器之间建立 tcp 连接,实现全双工通信 springboot 使用 websocket 有

    2023年04月14日
    浏览(58)
  • 一文带你如何用SpringBoot+RabbitMQ方式来收发消息

    预告了本篇的内容:利用RabbitTemplate和注解进行收发消息,还有一个我临时加上的内容:消息的序列化转换。 本篇会和SpringBoot做整合,采用自动配置的方式进行开发,我们只需要声明RabbitMQ地址就可以了,关于各种创建连接关闭连接的事都由Spring帮我们了~ 交给Spring帮我们管

    2024年02月09日
    浏览(32)
  • 一张思维导图带你学会SpringBoot使用AOP实现日志管理功能

    🧑‍💻作者名称:DaenCode 🎤作者简介:啥技术都喜欢捣鼓捣鼓,喜欢分享技术、经验、生活。 😎人生感悟:尝尽人生百味,方知世间冷暖。 📖所属专栏:SpringBoot实战 标题 一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码) 一张思维导图带你学会Springboot创

    2024年02月13日
    浏览(43)
  • 一张思维导图带你学会使用SpringBoot异步任务实现下单校验库存

    🧑‍💻作者名称:DaenCode 🎤作者简介:啥技术都喜欢捣鼓捣鼓,喜欢分享技术、经验、生活。 😎人生感悟:尝尽人生百味,方知世间冷暖。 📖所属专栏:SpringBoot实战 标题 一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码) 一张思维导图带你学会Springboot创

    2024年02月13日
    浏览(28)
  • 【Git】速食Git,一文学会Git使用

    版本控制是一种在开发的过程中用于管理我们对文件、目录或工程等内容的修改历史,方便查看更改历史记录,备份以便恢复以前的版本的软件工程技术。【通俗来说就跟我们所玩的游戏一样,不断地更新迭代游戏内容,比如赛季更新呀,新出皮肤呀等】 ①实现跨区域多人协

    2024年02月01日
    浏览(39)
  • 一文学会git常用命令和使用指南

    背景:最近有刚入职公司的小伙伴们总是在git使用过程中一系列问题,而且问题很多都是低级问题。所以我觉得有必要分享一个帖子,和大家学习一下。找了一下公司git管理规范文档,发现文档的描述不是很好理解,而且已经和现在的管理方式有一定的出入。所以我自行总结

    2024年02月14日
    浏览(32)
  • springboot+avue医院绩效考核系统源码

    医院绩效考核系统是一种以人力资源管理为基础,选用适合医院组织机构属性的绩效理论和方法,基于医院战略目标,构建全方位的绩效考评体系,在科学、合理的绩效管理体系基础上,采用科学管理的方法,如平衡计分卡的管理理念与方法,选取关键指标,对目标的执行进

    2024年02月08日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包