java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot+Avue短信通知功能

基于SpringBoot+Avue实现短信通知功能

作者:DaenCode

Avue是基于vue和element-ui的快速开发框架 ,它的核心是数据驱动UI的思想,让我们从繁琐的crud开发中解脱出来,本文将给大家介绍一下使用SpringBoot+Avue实现短信通知功能,文中有详细的代码示例,需要的朋友可以参考下

前置介绍

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平台接口的类。

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+Avue短信通知功能的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文