java实现阿里云接口发送短信验证码
程序员文章站
2022-06-04 16:21:37
...
版本
aliyun-java-sdk-core 4.4.6
aliyun-java-sdk-ecs 4.17.6
请求参数
返回数据
返回错误码请看我的另一篇文章 阿里云短信错误码
如何开通阿里云账号即开启短信服务 如何开启阿里云短信服务
示例
package com.ncst;
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 SendMs {
public static void main(String[] args) {
//随机验证码
int newcode = (int) (Math.random() * 9999) + 100;
//手机号
long num = 15028999627L;
CommonResponse response = sendMs(Integer.toString(newcode), Long.toString(num));
System.out.println(response.getData());
}
/**
* 发送短信
*
* @param code
* @param num
* @return
*/
public static CommonResponse sendMs(String code, String num) {
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "你的阿里云:AccessKey ID", "你的阿里云:AccessKey Secret");
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");
//必填:待发送手机号
request.putQueryParameter("PhoneNumbers", num);
//必填:短信签名-可在短信控制台中找到
request.putQueryParameter("SignName", "你的阿里云短信签名");
//必填:短信模板-可在短信控制台中找到
request.putQueryParameter("TemplateCode", "你的阿里云短信模板");
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
try {
CommonResponse response = client.getCommonResponse(request);
return response;
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
throw new RuntimeException("ERROR");
}
}
运行效果
上一篇: 宝宝不爱吃饭怎么办
下一篇: Python接口自动化框架