JAVA 基于阿里云平台的短信服务。由于在项目中使用了发送短信验证码的业务需求,经过了解和分析之后,我决定采用阿里云的短信服务。下面是我对于开启阿里云短信平台的介绍以及提供的阿里云的 JAVA 版本的测试代码。
一. 注册阿里云的账号
注册网址: 阿里云账号注册
二. 开通短信服务
开通短信服务 花费 35 元开通短信提醒资源包用于测试
三. 短信的设置
1. 设置短信签名 点击这里查看教程
2. 设置短信模板 点击这里查看教程
四. 测试代码
阿里云的 JAVA 测试代码
请看里面的标题 3(发布短信消息)
注: 测试代码里面的参数怎么获取在标题下面有说明
下面是我对于这段代码的修改
- /**** @param telephone :电话号码* @param templateCode :短信模板的编号* @param templateParamMap : key 短信模板的参数(${Param}), value 参数的值*/
- public static void sendSMS(String telephone, String templateCode, Map templateParamMap) { //1. 获取主题引用CloudAccount account = new CloudAccount("$YourAccessId", "$YourAccessKey", "$YourMNSEndpoint");MNSClient client = account.getMNSClient();CloudTopic topic = client.getTopicRef("$YourTopic");//2. 设置SMS消息体(必须)//注:目前暂时不支持消息体为空,需要指定消息内容,不为空即可RawTopicMessage msg = new RawTopicMessage();msg.setMessageBody("sms-message");//3. 生成SMS消息属性MessageAttributes messageAttributes = new MessageAttributes();BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();//3.1 设置发送短信的签名(SMSSignName)batchSmsAttributes.setFreeSignName("$YourSignName");//3.2 设置短信使用的模板batchSmsAttributes.setTemplateCode(templateCode);//3.3设置发送短信所使用的模板中参数对应得值(在模板中定义的,没有可以不设置)BatchSmsAttributes.SmsReceiverParams smsReceiverParams = new BatchSmsAttributes.SmsReceiverParams();for(String key: templateParamMap.keySet()){smsReceiverParams.setParam(key, templateParamMap.get(key));}//3.4增加接收短信的号码batchSmsAttributes.addSmsReceiver(telephone, smsReceiverParams);messageAttributes.setBatchSmsAttributes(batchSmsAttributes);try {//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();}finally{client.close();}}
来源: http://www.92to.com/bangong/2017/05-29/22371701.html