首先需要去阿里云网站申请短信模板(根据网站的新手引导进行注册验证),注册成功后,需要引入依赖或者jar包,然后进行编写代码
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.1.0</version>
</dependency>
系统产生随机位数的验证码(位数根据传来值length进行产生多少位的验证码)
public String randomNumber(int length){
if(length<1){
return "";
}
String[] arr={"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
StringBuffer bufString=new StringBuffer();
for(int i=0;i<length;i++){
bufString.append(arr[(int)Math.round(Math.random() * arr.length)]);
}
return bufString.toString();
}
发送短信验证码的方法:
private void sendMsg(String phone,String code){
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "阿里云用户的AccessKey ID", "阿里云用户的Access Key Secret");
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("PhoneNumbers", phone);
request.putQueryParameter("SignName", "签名名称");
request.putQueryParameter("TemplateCode", "模版CODE");
request.putQueryParameter("TemplateParam", "{'code':"+code+"}");
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}