进入阿里云平台,然后选择短信服务,通过API发送短信(需要充值金额,几块钱就可以,我们仅仅是小规模项目)
找到openAPI
可以看到Java语言的代码模板,这个就是Java SendSMS短信服务的代码
创建Accesskey
创建完成后
创建用户
添加权限
添加签名和模板
pom.xml文件中下载依赖
- <!-- 阿里云第三方依赖-->
- <dependency>
- <groupId>com.aliyun</groupId>
- <artifactId>aliyun-java-sdk-core</artifactId>
- <version>4.5.0</version>
- </dependency>
配置文件中配置参数
- aliyun.accessKeyID=用自己的!!!
- aliyun.accessSecret=用自己的!!!
SendSMS工具类
- package com.like.utils;
-
- 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;
- //import com.google.gson.Gson;
- //import java.util.*;
- //import com.aliyuncs.dysmsapi.model.v20170525.*;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Component;
- /*
- pom.xml
- <dependency>
- <groupId>com.aliyun</groupId>
- <artifactId>aliyun-java-sdk-core</artifactId>
- <version>4.6.0</version>
- </dependency>
- */
-
- @Component
- public class SMSUtils {
-
- @Value("${aliyun.accessKeyID}")
- private String accessKeyID;
- @Value("${aliyun.accessSecret}")
- private String accessKeySecret;
-
-
- public void sendSMS(String mobile,String code){
- // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
- DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_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",mobile);
- request.putQueryParameter("SignName","keke");
- request.putQueryParameter("TemplateCode","SMS_288145524");
- request.putQueryParameter("TemplateParam","{\"code\":\"" + code + "\"}");
-
- try {
- CommonResponse response = client.getCommonResponse(request);
- System.out.println(response.getData());
- } catch (ServerException e) {
- e.printStackTrace();
- } catch (ClientException e) {
- e.printStackTrace();
- }
- }
-
- }
-
-