java 调用阿里云SMS短信验证码接口


1、工具类

 1 import com.aliyuncs.DefaultAcsClient;
 2 import com.aliyuncs.IAcsClient;
 3 import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
 4 import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
 5 import com.aliyuncs.exceptions.ClientException;
 6 import com.aliyuncs.profile.DefaultProfile;
 7 import com.aliyuncs.profile.IClientProfile;
 8 import org.springframework.util.Assert;
 9 
10 /**
11  * 阿里云短信服务:
12  * 注意:需要 签名名称、模版CODE 以及 RAM访问控制中的 AccessKeyID 和 AccessKeySecret
13  */
14 public class AliyunSmsUtils {
15 
16     //产品名称
17     static final String PRODUCT = "Dysmsapi";
18     //产品域名
19     static final String DOMAIN = "dysmsapi.aliyuncs.com";
20 
21     static final String ACCESSKEYID = "";
22     static final String ACCESSKEYSECRET= "";
23 
24     public static SendSmsResponse sendSms(String telephone, String code) throws ClientException {
25         //可自助调整超时时间
26         System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
27         System.setProperty("sun.net.client.defaultReadTimeout", "10000");
28         //初始化acsClient,暂不支持region化
29         IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESSKEYID, ACCESSKEYSECRET);
30         DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", PRODUCT, DOMAIN);
31         IAcsClient acsClient = new DefaultAcsClient(profile);
32         //组装请求对象-具体描述见控制台-文档部分内容
33         SendSmsRequest request = new SendSmsRequest();
34         //必填:待发送手机号
35         request.setPhoneNumbers(telephone);
36         //必填:短信签名-可在短信控制台中找到
37         request.setSignName("");
38         //必填:短信模板-可在短信控制台中找到
39         request.setTemplateCode("");
40         request.setTemplateParam("{\"code\":\"" + code + "\"}");
41         // 扩展字段回执id
42 //        request.setOutId("");
43         SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
44         Assert.isTrue((sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")),"短信发送失败!");
45         return sendSmsResponse;
46     }
47 }
AliyunSmsUtils

2、调用示例

AliyunSmsUtils.sendSms("phonenumber", "23456");
sms