Java资源分享网 - 专业的Java学习网站 学Java,上Java资源分享网
阿里云短信验证码发送 PDF 下载
发布于:2024-03-02 11:17:33
(假如点击没反应,多刷新两次就OK!)

阿里云短信验证码发送  PDF 下载  图1

 

 

主要内容:

 

阿里云短信验证码获取

1.工具类生成验证码

 

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 {
//阿里云服务KEYID
private static final String KEYID = "******************";
//阿里云服务SECRET
private static final String SECRET = "*******************";
/**
* 使用AK&SK初始化账号Client
*/
public static Client createClient(String accessKeyId, String
accessKeySecret) throws Exception {
Config config = new Config()
// 必填,您的 AccessKey ID
.setAccessKeyId(accessKeyId)
// 必填,您的 AccessKey Secret
.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 {
// 创建一个短信服务客户端实例,使用预设的KEYID和SECRET进行身份认
证
Client client = SmsUtil.createClient(KEYID, SECRET);
// 创建SendSmsRequest对象,设置发送短信所需参数
SendSmsRequest sendSmsRequest = new SendSmsRequest()
// 设置接收短信的手机号码
.setPhoneNumbers(phone)
// 设置模板参数,根据实际业务场景替换为动态内容
.setTemplateParam(params)
// 设置短信模板CODE
.setTemplateCode(template_code)
// 设置短信签名名称
.setSignName("短信验证码");
// 调用客户端的sendSmsWithOptions方法发送短信,并传入
RuntimeOptions以配置额外的运行时选项
// 这段代码执行后会发送短信验证码到指定的手机号码上,但此处为了简洁
没有打印API返回的结果
client.sendSmsWithOptions(sendSmsRequest, new
RuntimeOptions());
} catch (Exception ignored) {
}
}
}