记录一下我项目中写的 发送验证码的代码。
@RequestMapping(value = "org/verification",method = RequestMethod.GET)
public void getVerificationCode(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "phone_number") String phoneNumber){
String sessionVerificationCode = (String) request.getSession().getAttribute(phoneNumber);
if(sessionVerificationCode!=null){
String[] codes = sessionVerificationCode.split("-");
Long createTime =Long.parseLong(codes[1]);
Long nowTime = System.currentTimeMillis();
if(nowTime-createTime>60000){
response.setHeader("status","400");
return;
}
}
DefaultProfile profile = DefaultProfile.getProfile("default", AliConstans.ACCESS_KEY_ID, AliConstans.ACCESS_SECRET);
IAcsClient client = new DefaultAcsClient(profile);
String code = AliConstans.getVerificationCode();
CommonRequest commonRequest = new CommonRequest();
commonRequest.setMethod(MethodType.POST);
commonRequest.setDomain("dysmsapi.aliyuncs.com");
commonRequest.setVersion("2019-08-12");
commonRequest.setAction("SendSms");
commonRequest.putQueryParameter("RegionId", "default");
commonRequest.putQueryParameter("PhoneNumbers", phoneNumber);
commonRequest.putQueryParameter("SignName", AliConstans.SIGN_NAME);
commonRequest.putQueryParameter("TemplateCode", AliConstans.TEMPLATE_CODE);
commonRequest.putQueryParameter("TemplateParam","{\"code\":\""+code+"\"}");
try{
CommonResponse commonResponse = client.getCommonResponse(commonRequest);
request.getSession().setAttribute(phoneNumber,code+"-"+System.currentTimeMillis());
response.setHeader("status","200");
System.out.println(commonResponse.getData());
} catch (ClientException e){
e.printStackTrace();
response.setHeader("status","500");
}
}
package com.sansanhealth.content;
import java.util.Random;
public class AliConstans {
/**
* Ram账号的AccessKey ID
*/
public static final String ACCESS_KEY_ID="";
/**
* RAM账号AccessKey Secret
*/
public static final String ACCESS_SECRET="";
/**
* 短信签名
*/
public static final String SIGN_NAME="";
/**
* 短信模板id
*/
public static final String TEMPLATE_CODE="";
public static String getVerificationCode(){
StringBuilder str = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 6; i++) {
str.append(random.nextInt(10));
}
return str.toString();
}
}