赞
踩
以下是一个使用Spring Boot实现手机短信发送的示例:
- <dependency>
- <groupId>com.aliyun</groupId>
- <artifactId>aliyun-java-sdk-sms</artifactId>
- <version>1.0.0</version>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- @Configuration
- public class SmsConfig {
- @Value("${aliyun.sms.accessKeyId}")
- private String accessKeyId;
-
- @Value("${aliyun.sms.accessKeySecret}")
- private String accessKeySecret;
-
- @Value("${aliyun.sms.regionId}")
- private String regionId;
-
- @Bean
- public IAcsClient acsClient() throws ClientException {
- IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
- DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Sms", "sms.aliyuncs.com");
- return new DefaultAcsClient(profile);
- }
- }
- @Service
- public class SmsService {
- @Value("${aliyun.sms.templateCode}")
- private String templateCode;
-
- @Value("${aliyun.sms.signName}")
- private String signName;
-
- @Autowired
- private IAcsClient acsClient;
-
- public void sendSms(String phoneNumber, String code) throws ClientException {
- SendSmsRequest request = new SendSmsRequest();
- request.setPhoneNumbers(phoneNumber); // 手机号码
- request.setSignName(signName); // 短信签名
- request.setTemplateCode(templateCode); // 短信模板ID
- request.setTemplateParam("{\"code\":\"" + code + "\"}"); // 短信模板变量替换JSON串
- SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
- System.out.println(sendSmsResponse.getMessage());
- }
- }
- @RestController
- public class SmsController {
- @Autowired
- private SmsService smsService;
-
- @PostMapping("/sms/send")
- public void sendSms(@RequestParam String phoneNumber, @RequestParam String code) throws ClientException {
- smsService.sendSms(phoneNumber, code);
- }
- }
- aliyun:
- sms:
- accessKeyId: <your accessKeyId>
- accessKeySecret: <your accessKeySecret>
- regionId: cn-hangzhou
- templateCode: <your templateCode>
- signName: <your signName>
启动应用程序,访问/sms/send
接口即可发送短信。注意:在实际使用中,需要替换掉<your accessKeyId>、<your accessKeySecret>、<your templateCode>和<your signName>等参数。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。