第一步:导入maven依赖包 dependency groupIdcom.aliyun/groupId artifactIdaliyun-java-sdk-core/artifactId version4.4.6/version /dependency 第二步:复制示例代码 package com . example . demo . sms ; import com . aliyuncs . Com
第一步:导入maven依赖包
<dependency><groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.4.6</version>
</dependency>
第二步:复制示例代码
package com.example.demo.sms;import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
public class SendSms {
public static void main(String[] args) {
final String accessKeyId = "阿里云AccessKeyId";
final String accessSecret = "阿里云AccessSecret";
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain("dysmsapi.aliyuncs.com");
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
//此处放接收验证码的手机号
String phone = "手机号码";
request.putQueryParameter("PhoneNumbers", phone);
//此处放签名名称(必须审核通过)
String signName = "短信签名名称";
request.putQueryParameter("SignName", signName);
//此处放短信模板(必须审核通过)
String templateCode = "短信模板Code";
request.putQueryParameter("TemplateCode", templateCode);
//此处放验证码的内容(JSON数据格式)
String templateParam = "{\"code\":\"" + "六位随机数字" + "\"}";
request.putQueryParameter("TemplateParam", templateParam);
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
}
第三步:测试发送
发送前请确保阿里云中的账户余额充足或购买了短信套餐包,否则就不能正常发送短信验证码。