短信平台对接
来源:互联网 发布:兔子软件安装器 编辑:程序博客网 时间:2024/06/10 09:16
阿里云上提供的DEMO比较混乱,这里的代码直接拿过去加入JAR就可以用
首先要购买阿里云的短信服务,获取必要的信息,然后使用以下代码
- import com.aliyun.mns.client.CloudAccount;
- import com.aliyun.mns.client.CloudTopic;
- import com.aliyun.mns.client.MNSClient;
- import com.aliyun.mns.common.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 = "https://41238.mns.cn-hangzhou.aliyuncs.com/"; //MNS域地址
- String topicName = "sms.topic-cn-hangzhou";
- String model = "SMS_7612321303";
- String signName = "xx公司";
-
-
-
-
- CloudAccount account = new CloudAccount(accessKeyId,accessKeySecret,endpoint);
- MNSClient client = account.getMNSClient();
- CloudTopic topic = client.getTopicRef(topicName);
-
-
-
-
-
- RawTopicMessage msg = new RawTopicMessage();
- msg.setMessageBody("sms-message");
-
-
-
-
- MessageAttributes messageAttributes = new MessageAttributes();
- BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();
-
- batchSmsAttributes.setFreeSignName(signName);
-
- batchSmsAttributes.setTemplateCode(model);
-
- BatchSmsAttributes.SmsReceiverParams smsReceiverParams = new BatchSmsAttributes.SmsReceiverParams();
- smsReceiverParams.setParam("code",message);
-
- batchSmsAttributes.addSmsReceiver(phone, smsReceiverParams);
- messageAttributes.setBatchSmsAttributes(batchSmsAttributes);
- try {
-
-
-
- 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包,可在阿里云官网去下载