Maven配置
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>3.7.1</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.1.0</version>
</dependency>
源码
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 App
{
static final String product = "Dysmsapi";
static final String domain = "dysmsapi.aliyuncs.com";
static final String accessKeyId = "accessKeyId填这里";
static final String accessKeySecret = "accessKeySecret填这里";
public static SendSmsResponse sendSms(String telephone, String code) throws ClientException
{
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
request.setPhoneNumbers(telephone);
request.setSignName("短信签名填这里");
request.setTemplateCode("短信模板填这里");
request.setTemplateParam("{\"code\":\"" + code + "\"}");
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK"))
{
System.out.println("短信发送成功!");
} else
{
System.out.println("短信发送失败!");
}
return sendSmsResponse;
}
private static int newcode;
public static int getNewcode()
{
return newcode;
}
public static void setNewcode()
{
newcode = (int) (Math.random() * 900000) + 100000;
}
public static void main(String[] args) throws Exception
{
setNewcode();
String code = Integer.toString(getNewcode());
System.out.println("六位数随机验证码为:" + code);
SendSmsResponse sendSms = sendSms("手机号码填这里", code);
System.out.println("短信接口返回的数据----------------");
System.out.println("Code=" + sendSms.getCode());
System.out.println("Message=" + sendSms.getMessage());
System.out.println("RequestId=" + sendSms.getRequestId());
System.out.println("BizId=" + sendSms.getBizId());
}
参考来源
java 阿里云接口实现发送短信验证码