阿里云短信平台对接

编程入门 行业动态 更新时间:2024-10-09 00:45:26

<a href=https://www.elefans.com/category/jswz/34/1770131.html style=阿里云短信平台对接"/>

阿里云短信平台对接

经过两天研究终于完成了阿里云短信平台对接开发,阿里云上提供的DEMO比较混乱,这里的代码直接拿过去加入JAR就可以用

 

首先要购买阿里云的短信服务,获取必要的信息,然后使用以下代码

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mnsmon.ServiceException;
import com.aliyun.mns.model.BatchSmsAttributes;
import com.aliyun.mns.model.MessageAttributes;
import com.aliyun.mns.model.RawTopicMessage;
import com.aliyun.mns.model.TopicMessage;public class AlyMessage {public static void sendMessage(String phone,String message){/***以下信息必填,否则可能出现推送成功,但无法收到短信的情况*/String accessKeyId = "";        //密匙String accessKeySecret = "";   //密匙String endpoint = "/";  //MNS域地址String topicName = "sms.topic-cn-hangzhou"; //主题String model = "SMS_7612321303";   //短信模板String signName = "xx公司";   //短信签名/*** Step 1. 获取主题引用*/CloudAccount account = new CloudAccount(accessKeyId,accessKeySecret,endpoint);MNSClient client = account.getMNSClient();CloudTopic topic = client.getTopicRef(topicName);/*** Step 2. 设置SMS消息体(必须)* 注:目前暂时不支持消息内容为空,需要指定消息内容,不为空即可。*/RawTopicMessage msg = new RawTopicMessage();msg.setMessageBody("sms-message");/*** Step 3. 生成SMS消息属性*/MessageAttributes messageAttributes = new MessageAttributes();BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();// 3.1 设置发送短信的签名(SMSSignName)batchSmsAttributes.setFreeSignName(signName);// 3.2 设置发送短信使用的模板(SMSTempateCode)batchSmsAttributes.setTemplateCode(model);// 3.3 设置发送短信所使用的模板中参数对应的值(在短信模板中定义的,没有可以不用设置)BatchSmsAttributes.SmsReceiverParams smsReceiverParams = new BatchSmsAttributes.SmsReceiverParams();smsReceiverParams.setParam("code",message);// 3.4 增加接收短信的号码batchSmsAttributes.addSmsReceiver(phone, smsReceiverParams);messageAttributes.setBatchSmsAttributes(batchSmsAttributes);try {/*** Step 4. 发布SMS消息*/TopicMessage ret = topic.publishMessage(msg, messageAttributes);System.out.println("MessageId: " + ret.getMessageId());System.out.println("MessageMD5: " + ret.getMessageBodyMD5());} catch (ServiceException se) {System.out.println(se.getErrorCode() + se.getRequestId());System.out.println(se.getMessage());se.printStackTrace();} catch (Exception e) {e.printStackTrace();}client.close();}public static void main(String[] args) {sendMessage("11232137", "123456");}}

所需要的jar包,可在阿里云官网去下载


更多推荐

阿里云短信平台对接

本文发布于:2024-02-19 16:55:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1765145.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:阿里   短信平台

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!