springboot2.x接入阿里云市场短信发送的实现
短信预约 -IT技能 免费直播动态提醒
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(ClientHttpRequestFactory requestFactory){
return new RestTemplate(requestFactory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(10000);
factory.setConnectTimeout(10000);
return factory;
}
}
增加配置
@ConfigurationProperties(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;
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.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");
}
}
发送成功咯
到此这篇关于springboot2.x 接入阿里云市场短信发送的实现的文章就介绍到这了,更多相关springboot 阿里云短信发送内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341