基于SpringBoot+Avue實(shí)現(xiàn)短信通知功能
前置介紹
Avue是基于vue和element-ui的快速開發(fā)框架 。它的核心是數(shù)據(jù)驅(qū)動(dòng)UI的思想,讓我們從繁瑣的crud開發(fā)中解脫出來(lái),它的寫法類似easyUI,但是寫起來(lái)比easyui更容易,因?yàn)樗腔A(chǔ)數(shù)據(jù)雙向綁定以及其他vue的特性。同時(shí)不知局限于crud,它還有我們經(jīng)常用的一些組件例如,表單,數(shù)據(jù)展示卡,人物展示卡等等組件。
一.官網(wǎng)參照
云MAS業(yè)務(wù)平臺(tái)_中國(guó)移動(dòng)

二.實(shí)現(xiàn)方式
基于HTTPS方式云MAS平臺(tái)
三.使用文檔
可以在云MAS官網(wǎng)進(jìn)行下載,下方文檔存放在了我的語(yǔ)雀筆記中。下載時(shí)注意下載HTTPS文檔,內(nèi)含接口使用規(guī)范。

四.代碼實(shí)現(xiàn)
4.1.接口對(duì)接代碼
4.1.1.SMSHttpClient.java—接口調(diào)用
此類為對(duì)接云MAS平臺(tái)接口的類。
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 = "";//集團(tuán)名稱 接口聯(lián)調(diào)賬號(hào) zsywz
private static String sign = "";//網(wǎng)關(guān)簽名編碼
private static String addSerial = "106509773";//拓展碼 填空
private static String templateid = "";//模板ID
public static String msg = "123456";
public static String url = "https://****:28888/sms/tmpsubmit";//請(qǐng)求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("發(fā)送短信參數(shù):"+reqText);
String encode = Base64.encodeBase64String(reqText.getBytes("UTF-8"));
System.out.println("發(fā)送短信base64:"+encode);
//System.out.println(encode);
String resStr = sendPost(url,encode);
System.out.println("發(fā)送短信結(jié)果:"+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方法測(cè)試發(fā)送短信,返回1表示成功,0表示失敗
*/
public static void main(String[] args) throws UnsupportedEncodingException {
int result = sendMsg("手機(jī)號(hào)",msg);
System.out.println(result);
// System.out.println( Md5Util.MD5(Hex.encodeHexString("demo0123qwe38516fabae004eddbfa3ace1d419469613800138000[\"abcde\"]4sEuJxDpC".getBytes(StandardCharsets.UTF_8))));
}
/**
* 向指定 URL 發(fā)送POST方法的請(qǐng)求
*
* @param url
* 發(fā)送請(qǐng)求的 URL
* @param param
* 請(qǐng)求參數(shù)
* @return 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果
*/
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";
// 創(chuàng)建信任管理器
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;
} //將所有驗(yàn)證的結(jié)果都設(shè)為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—請(qǐng)求實(shí)體
此類為發(fā)送短信的請(qǐng)求實(shí)體。
/**
* 發(fā)送短信請(qǐng)求實(shí)體
*/
public class SendReq {
private String ecName;//集團(tuán)客戶名稱
private String apId;//用戶名
private String secretKey;//密碼
private String mobiles;//手機(jī)號(hào)碼逗號(hào)分隔。(如“18137282928,18137282922,18137282923”)
// private String content;//發(fā)送短信內(nèi)容
private String params;//發(fā)送短信內(nèi)容
private String sign;//網(wǎng)關(guān)簽名編碼,必填,簽名編碼在中國(guó)移動(dòng)集團(tuán)開通帳號(hào)后分配,可以在云MAS網(wǎng)頁(yè)端管理子系統(tǒng)-SMS接口管理功能中下載。
private String addSerial;//擴(kuò)展碼,根據(jù)向移動(dòng)公司申請(qǐng)的通道填寫,如果申請(qǐng)的精確匹配通道,則填寫空字符串(""),否則添加移動(dòng)公司允許的擴(kuò)展碼。
private String mac;//API輸入?yún)?shù)簽名結(jié)果,簽名算法:將ecName,apId,secretKey,mobiles,content ,sign,addSerial按照順序拼接,然后通過md5(32位小寫)計(jì)算后得出的值。
/**
* 模板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—響應(yīng)實(shí)體
此類為發(fā)送短信的響應(yīng)實(shí)體。
/**
* 發(fā)送短信響應(yīng)實(shí)體
*/
public class SendRes {
private String rspcod;//響應(yīng)碼
private String msgGroup;//消息批次號(hào),由云MAS平臺(tái)生成,用于驗(yàn)證短信提交報(bào)告和狀態(tài)報(bào)告的一致性(取值msgGroup)注:如果數(shù)據(jù)驗(yàn)證不通過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.功能實(shí)現(xiàn)代碼
此JS文件為Avue框架中封裝的統(tǒng)一JS文件,在此文件中存放統(tǒng)一業(yè)務(wù)的前端接口。
4.2.1.封裝統(tǒng)一接口js文件
export const noteCompany = (itemType) => {
return request({
url: '接口地址',
method: 'post',
params: {
itemType,
}
})
}4.2.2.功能頁(yè)面文件
此文件為頁(yè)面文件中功能按鈕部分代碼(觸發(fā)發(fā)送短信的功能按鈕)
//按鈕
<el-button :type="type"
icon="el-icon-check"
:size="size"
@click.native="note(row)">短信通知
</el-button>
//方法,根據(jù)類型匹配查出相應(yīng)接收短信的人員
note(row){
noteCompany(row.itemType).then(() => {
this.onLoad(this.page);
this.$message({
type: "success",
message:"成功發(fā)送"
});
}
);
},4.2.3.Controller層接口
下方為后端代碼中Controller層觸發(fā)短信功能的代碼。
/**
* 短信通知
*/
@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("成功發(fā)送"+companyIds.size()+"信息");
}以上就是基于SpringBoot+Avue實(shí)現(xiàn)短信通知功能的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot+Avue短信通知功能的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java實(shí)現(xiàn)文件夾中內(nèi)容定時(shí)刪除
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)文件夾中內(nèi)容定時(shí)刪除,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
Java中實(shí)現(xiàn)String.padLeft和String.padRight的示例
本篇文章主要介紹了Java中實(shí)現(xiàn)String.padLeft和String.padRight,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2017-09-09
SpringCloud實(shí)現(xiàn)灰度發(fā)布的方法步驟
本文主要介紹了SpringCloud實(shí)現(xiàn)灰度發(fā)布的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05
Java RPC框架如何實(shí)現(xiàn)客戶端限流配置
這篇文章主要介紹了Java RPC框架如何實(shí)現(xiàn)客戶端限流配置,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
Java Quartz觸發(fā)器CronTriggerBean配置用法詳解
這篇文章主要介紹了Java Quartz觸發(fā)器CronTriggerBean配置用法詳解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08

