完整代码都在最后,可以直接更换使用
先在阿里云开通短信服务器
签名管理和模板管理必须通过才能发送短信 链接地址
签名和模板都好了之后查看API Demo
参数填写完发送成功之后复制右边的代码到IDEA,报错的Sys去除
pom依赖
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.0.3</version>
</dependency>
这个时候我们复制过来运行就报这样一个错误
com.aliyuncs.exceptions.ClientException: InvalidAccessKeyId : Specified access key is not found or invalid.
RequestId : 9F22D544-DAC7-4221-B883-B5A42A2B9931
at com.aliyuncs.DefaultAcsClient.getCommonResponse(DefaultAcsClient.java:177)
at com.cloopen.SendSms.main(SendSms.java:37)
Process finished with exit code 0
问题在这里
需要开通AccessKey管理 AccessKey链接地址
开通完之后获得AccessKey ID 和 AccessKey Secret
替换刚才的两个地方,在运行就发送成功了。
注意记得把两边的<>括号去掉
生成随机数
//生成6位随机数字
System.out.println((int)((Math.random()*9+1)*100000));
//生成5位随机数字
System.out.println((int)((Math.random()*9+1)*10000));
//生成4位随机数字
System.out.println((int)((Math.random()*9+1)*1000));
//生成3位随机数字
System.out.println((int)((Math.random()*9+1)*100));
//生成2位随机数字
System.out.println((int)((Math.random()*9+1)*10));
//生成1位随机数字
System.out.println((int)((Math.random()*9+1)));
pom依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
生成6位随机数
Integer number= (int)((Math.random()*9+1)*100000);
Map<String,Object> map = new HashMap<String,Object>();
map.put("code",number);
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
完整6位验证码代码
package com.util;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import java.util.HashMap;
import java.util.Map;
public class SendSms {
public static void main(String[] args) {
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "AccessKey ID****************", "AccessKey Secret**************");
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("PhoneNumbers", "138********");//手机号码
request.putQueryParameter("SignName", "ABC商城");//签名名称
request.putQueryParameter("TemplateCode", "SMS_*********");//签名模版CODE
//生成6位随机数字
Integer number= (int)((Math.random()*9+1)*100000);
Map<String,Object> map = new HashMap<String,Object>();
map.put("code",number);
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));//验证码
//如果不想加上面随机验证码注释上面4行,去除下面注解即可
//request.putQueryParameter("TemplateParam", "{\"code\":\"666666\"}");
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ClientException e) {
e.printStackTrace();
}
}
}