所有云平台短信服务不再向个人开放了.....
使用前导入相关开发包
<!--阿里云短信sdk-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.0.6</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.1.0</version>
</dependency>
引入的jar包会导致,不过没什么影响
[WARN][2019-01-07 20:02:07] Failed to scan [file:/F:/m2/com/sun/xml/bind/jaxb-impl/2.1/jaxb1-impl.jar] from classloader hierarchy
java.io.FileNotFoundException: F:m2comsunxmlindjaxb-impl2.1jaxb1-impl.jar (系统找不到指定的文件。)
测试程序
@Controller
@RequestMapping("/identify")
public class MsgCodeController {
@RequestMapping("/code")
@ResponseBody
public void getCode(String phone) {
//随机生成四位数验证码
char[] array = "0123456789".toCharArray();
StringBuilder sbu = new StringBuilder();
Random random = new Random();
int cycleLength = 4;
for (int i = 1; i <= cycleLength; i++) {
int index = random.nextInt(array.length);
sbu.append(array[index]);
}
String codeContain = sbu.toString();
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
final String product = "Dysmsapi";//短信API产品名称(短信产品名固定,无需修改)
final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名(接口地址固定,无需修改)
final String accessKeyId = "";//你的accessKeyId,参考本文档步骤2
final String accessKeySecret = "";//你的accessKeySecret,参考本文档步骤2
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
accessKeySecret);
try {
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
} catch (ClientException e) {
e.printStackTrace();
}
IAcsClient acsClient = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
request.setMethod(MethodType.POST);
request.setPhoneNumbers(phone);
request.setSignName("短信签名");
request.setTemplateCode("模板编号");
//request.setTemplateParam("{"code":"8888"}");
String prefix = "{code:" + codeContain + "}";
//codeContain设置到redis,并设置失效时间
request.setTemplateParam(prefix);
request.setOutId("yourOutId");
SendSmsResponse sendSmsResponse = null;
try {
sendSmsResponse = acsClient.getAcsResponse(request);
} catch (ClientException e) {
e.printStackTrace();
}
if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
}
}
}