使用阿里云发送验证码短信完整代码
每次创建成功Accesskey之后,AccessKey Secret只会 显示一次,所以要保存一下,下次就看不见了,但是如果没有保存,删了重新创一个就完事了
package com.example.demo.com;
import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
public class SMStest {
public static void main(String[] args) {
SendSmsResponse sendSms = sendSms();
if(sendSms.getCode().equals("OK")) {
System.out.println("短信发送成功...."+sendSms.getCode());
}else {
System.out.println("短信发送失败...."+sendSms.getCode());
}
}
static final String product = "Dysmsapi";
//产品域名,开发者无需替换
static final String domain = "dysmsapi.aliyuncs.com";
// TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
static final String accessKeyId = "需填写";
static final String accessKeySecret = "需填写";
public static SendSmsResponse sendSms() throws ClientException {
//可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
try {
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
} catch (com.aliyuncs.exceptions.ClientException e) {
throw new RuntimeException(e);
}
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
//必填:待发送手机号 如果是测试签名,则需要在阿里云中添加该手机号
request.setPhoneNumbers("发送的手机号");
//必填:短信签名-可在短信控制台中找到 Sendmessage
request.setSignName("你的签名");
//必填:短信模板-可在短信控制台中找到
// request.setTemplateCode("SMS_279090037");
//可选:模板中的变量替换JSON串,可以根据模板创建实体或者toJsonString
String node="54188";
request.setTemplateParam("{\"code\":\"1234\"}");
// request.setSignName("阿里云短信测试");
request.setTemplateCode("SMS_461000096");
//选填-上行短信扩展码(无特殊需求用户请忽略此字段)
//request.setSmsUpExtendCode("90997");
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
// request.setOutId("yourOutId");
//hint 此处可能会抛出异常,注意catch
SendSmsResponse sendSmsResponse = null;
try {
sendSmsResponse = acsClient.getAcsResponse(request);
} catch (com.aliyuncs.exceptions.ClientException e) {
throw new RuntimeException(e);
}
return sendSmsResponse;
}
}