阿里云官网注册登录
找到短信服务并开通
打开短信服务的管理台
在国内消息那栏中添加签名管理和模板管理(按照格式要求去写)
pom.xml
<dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.5.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies>
实现的工具类
其中需要修改的一些参数已经标出
package com.zbw.demo; 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 net.minidev.json.JSONObject; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import java.rmi.ServerException; import java.util.HashMap; @SpringBootTest class DemoApplicationTests { @Test void contextLoads() { //连接 DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "你的AccessKeyid", "你的AccessKey密码"); 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("PhoneNumbers", "收到验证码的电话号码"); request.putQueryParameter("SignName", "你的阿里云签名的名称"); request.putQueryParameter("TemplateCode", "你的阿里云模板Code"); //构建验证码 HashMap<String, Object> map = new HashMap<>(); map.put("code", 这里写你想要给手机上发的验证码); request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map)); try { CommonResponse response = client.getCommonResponse(request); System.out.println(response.getData()); } catch (ClientException e) { e.printStackTrace(); } } }
原文链接:https://www.cnblogs.com/zbbobo/p/13266364.html