阿里云短信平台对接"/>
阿里云短信平台对接
经过两天研究终于完成了阿里云短信平台对接开发,阿里云上提供的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包,可在阿里云官网去下载
更多推荐
阿里云短信平台对接
发布评论