用阿里云发短信,验证码是6位,如果随机生成的第一位是0,那么发到手机上就会变成5位,0会被干掉。解决方案如下:
//引入json import net.sf.json.JSONObject;
SmsResponse smsResponse=new SmsResponse();
StringBuilder validateCode = new StringBuilder();
for (int i = 0; i < 6; i++) {
int random = (int) (Math.random() * 10);
validateCode.append(Integer.valueOf(random).toString());
}
logger.info("phone:"+phone+"发送的验证码为:"+validateCode);
smsResponse.setValidateCode(validateCode.toString());
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
// request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
HashMap<String,String> map=new HashMap<>();
map.put("code",validateCode.toString());
JSONObject jsonObject = JSONObject.fromObject(map);
request.setTemplateParam(jsonObject.toString());