springboot2.x 接入阿里云市场短信发送的实现

网友投稿 253 2022-09-12


springboot2.x 接入阿里云市场短信发送的实现

1.短信平台购买次数地址

https://market.aliyun.com/products/57000002/cmapi00046920.html

提供测试模板、免审核、测试成本更低

2.测试学习使用的话,3块钱75多次够用了

3.购买后在跳转成功页面记录

AppSecret、key、code

4.记录模板ID

5.上代码环节

@Configuration

public class RestTemplateConfig {

@Bean

public RestTemplate restTemplate(ClientHttpRehttp://questFactory requestFactory){

return new RestTemplate(requestFactory);

}

@Bean

public ClientHttpRequestFactory simpleClientHttpRequestFactory(){

SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();

factory.sevsqyKtReadTimeout(10000);

factory.setConnecthttp://Timeout(10000);

return factory;

}

}

增加配置

@ConfigurationPropertieshttp://(prefix = "sms")

@Configuration

@Data

public class SmsConfig {

private String templateId;

private String appCode;

}

application.yml

发送类

@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;vsqyK

/**

* 发送短信验证码

* @param to

* @param templateId

* @param value

*/

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 response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

log.info("url={},body={}",url,response.getBody());

if(response.getStatusCode().is2xxSuccessful()){

log.info("发送短信验证码成功");

}else {

log.error("发送短信验证码失败:{}",response.getBody());

}

}

}

测试类验证

@RunWith(SpringRunner.class)

@SpringBootTest(classes = AccountApplication.class)

@Slf4j

public class SmsTest {

@Autowired

private SmsComponent smsComponent;

@Autowired

private SmsConfig smsConfig;

@Test

public void testSendSms(){

smsComponent.send("138XXXXXXX",smsConfig.getTemplateId(),"666888");

}

}

发送成功咯


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:计算机网络之数据传输过程(网络中数据传输的过程)
下一篇:小白入门计算机网络(计算机网络入门基础知识)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~