易优评实现短信发送Demo 1.购买短信服务 我们需要在相关短信平台上购买服务,推荐一下三个平台
短信平台:
阿里云:https://www.aliyun.com/product/sms
* 推荐
腾讯云:https://cloud.tencent.com/product/sms
* 推荐
第三方厂商:
https://market.aliyun.com/products/57000002/cmapi00046920.html
* 提供测试模板、免审核、测试成本更低
已第三个短信平台为例:
如图所示价格表,根据自己的需求购买。购买成功后会在已购买服务内看到购买的产品:
2.功能实现
项目结构:
0.导入必须的依赖 1 2 3 4 5 6 7 8 9 10 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-test</artifactId > <scope > test</scope > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-configuration-processor</artifactId > <optional > true</optional > </dependency >
1.在springboot的配置文件中配置短信发送的相关信息
2.app-code在购买的服务内有,template-id在如下图找到
上图提到的Query请求参数表示拼接在url上的。
3.编写配置类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate (ClientHttpRequestFactory factory) { return new RestTemplate (factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory () { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory (); factory.setReadTimeout(10000 ); factory.setConnectTimeout(10000 ); return factory; } }
4.读取短信配置参数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 @ConfigurationProperties(prefix = "sms") @Configuration @Data public class SmsConfig { private String templateId; private String appCode; }
5.编写相关组件类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 @Component @Slf4j public class SmsComponent { private static final String URL_TEMPLATE = "https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s" ; @Autowired private RestTemplate restTemplate; @Autowired private SmsConfig smsConfig; public void send (String to,String templateId,String value) { String url = String.format(URL_TEMPLATE,to,templateId,value); HttpHeaders headers = new HttpHeaders (); headers.set("Authorization" , "APPCODE " + smsConfig.getAppCode()); HttpEntity entity = new HttpEntity (headers); ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); log.info("url={},body={}" ,url,response.getBody()); if (response.getStatusCode().is2xxSuccessful()){ log.info("发送短信验证码成功" ); }else { log.info("发送短信验证码失败:{}" ,response.getBody()); } } }
6.测试 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @RunWith(SpringRunner.class) @SpringBootTest(classes = RuoYiApplication.class) public class SmsTest { @Autowired private SmsComponent smsComponent; @Autowired private SmsConfig smsConfig; @Test public void testSendSms () { smsComponent.send("15188753131" ,smsConfig.getTemplateId(),"855" ); } }
注意:在最后的发送验证码内容必须是六位及以下的数字,不然会报错
1 org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: [{"data" :{},"msg" :"测试验证码短信变量必须是6位或以下数字" ,"success" :false ,"code" :400 ,"charge" :false }]
测试成功