阿里云短信服务接口
阿里云短信服务(Short Message Service)是阿里云为用户提供的一种通信服务的能力。
支持向国内和国际快速发送验证码、短信通知和推广短信,服务范围覆盖全球200多个国家和地区。国内短信支持三网合一专属通道,与工信部携号转网平台实时互联。电信级运维保障,实时监控自动切换,到达率高达99%。完美支撑双11期间20亿短信发送,6亿用户触达。
快速开发
①开启短信服务
1)登陆阿里云服务平台

2)选择控制台

3)点击左上角下拉按钮选择短信服务

4)开通短信服务

②实名认证
1)如果没有实名认证需要跳转实名认证界面

2)选择相应的认证

3)选择支付宝快速的认证

③创建签名与模板
1)添加签名

2)选择签名使用场景
验证码:只能使用验证码模板
通用:都可以使用(申请较为严格)

3)创建短信模板

4)根据常用模板库申请相应短信模板
根据使用签名可以创建相应模板,注意:验证码签名只能使用验证码模板

④完成前期的准备工作
1)获取申请成功的签名(注册时的签名名称)

2)获取申请成功的短信模板(模版code)

3)获取AccessKey ID 和 AccessKey Secret

⑤代码书写
1)导入相应坐标
<dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-dysmsapi</artifactId> <version>1.0.0</version> </dependency>
2)创建短信发送工具类
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.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
public class SendSms {
private static final String AccessKeyId = "";//你的accessKeyId
private static final String AccessKeySecret = "";//你的accessKeySecret
private static final String SignName = "";//使用的签名
private static final String TemplateCode = "";//发送短信使用的模板
private static IAcsClient acs = null;//服务对象
private static SendSmsRequest req = new SendSmsRequest();//短信发送请求对象
static {
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", AccessKeyId, AccessKeySecret);
acs = new DefaultAcsClient(profile);
}
//随机生成指定位数验证码
public static StringBuffer randomCode(int number){
//验证码内容集
final char[] CHARS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
StringBuffer stringBuffer=new StringBuffer();
Random r=new Random();
for(int i=0;i<number;i++){
stringBuffer.append(CHARS[r.nextInt(CHARS.length)]);
}
return stringBuffer;
}
//自定义发送方法
public static boolean sendCode(String mobile, String code) throws ClientException {
req.setPhoneNumbers(mobile);//设置接收短信手机号
req.setSignName(SignName);//设置使用签名
req.setTemplateCode(TemplateCode);//设置使用通知模板id
req.setTemplateParam("{\"code\":\"" + code + "\"}");//设置请求参数 以json字符串形式与模板一致
SendSmsResponse res = acs.getAcsResponse(req);//向服务器发送请求
//System.out.println("res code: " + res.getCode());//响应状态码
// System.out.println("res message: " + res.getMessage());//响应信息
if (res.getCode() == null && !res.getCode().equals("OK")) {
System.out.println(res.getMessage());
return false;
}
return true;
}
public static void main(String[] args) throws ClientException {
System.out.println(sendCode("手机号","验证码"));
}
}
更多请查看阿里短信服务手册
阿里短信服务手册
到此这篇关于Java实现阿里云短信接口的示例的文章就介绍到这了,更多相关Java 阿里云短信接口内容请搜索本网站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本网站!
您可能感兴趣的文章:
- 详细介绍Java阿里云的短信验证码实现