public class VerificationCodeUtil{
/**
* 六位随机数验证码
*/
public static String getVerificationCode() {
StringBuilder result = new StringBuilder();
Random random = new Random();
String[] str = {"0", "1", "2", "3", "4", "5", "6", "7",
"8", "9"};
for (int i = 0; i < 6; i++) {
result.append(str[random.nextInt(10)]);
}
return result.toString();
}
}
2.短信验证码发送工具类
public class SmsUtil {
private static final String KEYID = "******************";
private static final String SECRET = "*******************";
/**
* 使用AK&SK初始化账号Client
*/
public static Client createClient(String accessKeyId, String
accessKeySecret) throws Exception {
Config config = new Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
config.endpoint = "dysmsapi.aliyuncs.com";
return new Client(config);
}
/**
* 短信验证码
*
* @param phone 手机号
* @param template_code 短信模板
* @param params 模板参数
*/
public static void sendMessage(String phone, String
template_code, String params) {
try {
证
Client client = SmsUtil.createClient(KEYID, SECRET);
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(phone)
.setTemplateParam(params)
.setTemplateCode(template_code)
.setSignName("短信验证码");
RuntimeOptions以配置额外的运行时选项
没有打印API返回的结果
client.sendSmsWithOptions(sendSmsRequest, new
RuntimeOptions());
} catch (Exception ignored) {
}
}
}