1)查看 API Demo

image.png
image.png

2)新建一个SpringBoot项目 sms-verification


3)引入依赖

  1. <!--aliyun-->
  2. <dependency>
  3. <groupId>com.aliyun</groupId>
  4. <artifactId>aliyun-java-sdk-core</artifactId>
  5. <version>4.5.3</version>
  6. </dependency>
  7. <!--fastjson-->
  8. <dependency>
  9. <groupId>com.alibaba</groupId>
  10. <artifactId>fastjson</artifactId>
  11. <version>1.2.73</version>
  12. </dependency>
  13. <!--redis-->
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-data-redis</artifactId>
  17. </dependency>

4)编写一个测试类,就把刚刚的 API Demo 复制过来进行修改

  1. package com.gmw.sms;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.aliyuncs.CommonRequest;
  4. import com.aliyuncs.CommonResponse;
  5. import com.aliyuncs.DefaultAcsClient;
  6. import com.aliyuncs.IAcsClient;
  7. import com.aliyuncs.exceptions.ClientException;
  8. import com.aliyuncs.exceptions.ServerException;
  9. import com.aliyuncs.http.MethodType;
  10. import com.aliyuncs.profile.DefaultProfile;
  11. import org.junit.jupiter.api.Test;
  12. import org.springframework.boot.test.context.SpringBootTest;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. import java.util.UUID;
  16. @SpringBootTest
  17. class SmsApplicationTests {
  18. @Test
  19. void contextLoads() {
  20. /**
  21. * 第一个参数默认填写就行
  22. * 第二个参数表示"<accessKeyId>"
  23. * 第三个参数表示"<accessSecret>"
  24. */
  25. // 这里的 AccessKey ID 、 Secret就是 阿里云用户对于的值,复制过来即可
  26. DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>");
  27. IAcsClient client = new DefaultAcsClient(profile);
  28. //设置相关固定的参数
  29. CommonRequest request = new CommonRequest();
  30. request.setSysMethod(MethodType.POST);
  31. request.setSysDomain("dysmsapi.aliyuncs.com");
  32. request.setSysVersion("2017-05-25");
  33. request.setSysAction("SendSms");
  34. //构造参数
  35. Map<String,Object> param = new HashMap<>();
  36. String code = UUID.randomUUID().toString().substring(0,4);
  37. param.put("code",code);
  38. //设置发送相关的参数
  39. request.putQueryParameter("PhoneNumbers","手机号"); //手机号
  40. request.putQueryParameter("SignName","申请阿里云 签名名称"); //申请阿里云 签名名称
  41. request.putQueryParameter("TemplateCode","申请阿里云 模板code"); //申请阿里云 模板code
  42. request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); //验证码数据,转换json数据传递
  43. try {
  44. CommonResponse response = client.getCommonResponse(request);
  45. System.out.println(response.getData());
  46. } catch (ServerException e) {
  47. e.printStackTrace();
  48. } catch (ClientException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. }

5)最后就可以得到短信了

注意:

如果上面自定义的参数名写错,不会成功 如果 模板、签名 没有通过审核会报错>