当前位置:   article > 正文

springboot 集成短信发送功能(人工智能编写)_springboot集成短信发送功能

springboot集成短信发送功能

要在Spring Boot中集成短信发送功能,你可以使用第三方的短信服务提供商的API来实现。以下是一个基本的示例代码,我是通过chatGPT4.0一键生成代码。

1. 添加依赖:在pom.xml文件中添加相应的短信服务提供商的SDK依赖,例如阿里云的aliyun-java-sdk-dysmsapi

  1. <dependency>
  2. <groupId>com.aliyun</groupId>
  3. <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
  4. <version>最新版本号</version>
  5. </dependency>

2. application.propertiesapplication.yml中配置短信服务的相关参数,如阿里云短信服务的AccessKey、Secret等。

3. 创建一个短信发送的服务类,例如SmsService

  1. import com.aliyuncs.DefaultAcsClient;
  2. import com.aliyuncs.exceptions.ClientException;
  3. import com.aliyuncs.profile.DefaultProfile;
  4. import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
  5. import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
  6. @Service
  7. public class SmsService {
  8. @Value("${sms.accessKeyId}")
  9. private String accessKeyId;
  10. @Value("${sms.accessKeySecret}")
  11. private String accessKeySecret;
  12. @Value("${sms.signName}")
  13. private String signName;
  14. @Value("${sms.templateCode}")
  15. private String templateCode;
  16. public boolean sendSms(String phoneNumber, String message) {
  17. DefaultProfile profile = DefaultProfile.getProfile("default", accessKeyId, accessKeySecret);
  18. DefaultAcsClient client = new DefaultAcsClient(profile);
  19. SendSmsRequest request = new SendSmsRequest();
  20. request.setPhoneNumbers(phoneNumber);
  21. request.setSignName(signName);
  22. request.setTemplateCode(templateCode);
  23. request.setTemplateParam(message);
  24. try {
  25. SendSmsResponse response = client.getAcsResponse(request);
  26. return response.getCode().equals("OK");
  27. } catch (ClientException e) {
  28. e.printStackTrace();
  29. }
  30. return false;
  31. }
  32. }

在上述代码中,我们使用阿里云短信服务的SDK来发送短信。在sendSms方法中,我们通过配置文件获取AccessKey、Secret、短信签名和短信模板的编码,并将手机号码和短信内容作为参数传入。

4. 在需要发送短信的地方调用SmsService的方法来发送短信。

  1. @RestController
  2. @RequestMapping("/api")
  3. public class SmsController {
  4. @Autowired
  5. private SmsService smsService;
  6. @PostMapping("/sms/send")
  7. public ResponseEntity<String> sendSms(@RequestParam String phoneNumber, @RequestParam String message) {
  8. boolean result = smsService.sendSms(phoneNumber, message);
  9. if (result) {
  10. return ResponseEntity.ok("短信发送成功");
  11. } else {
  12. return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("短信发送失败");
  13. }
  14. }
  15. }

在上述代码中,我们创建了一个RESTful接口/api/sms/send,接收手机号码和短信内容作为参数,并调用SmsServicesendSms方法发送短信。根据发送结果返回相应的响应。

请注意,以上示例代码仅为参考,具体的实现方式可能会根据你所选择的短信服务提供商和其API进行调整。另外,还需要在相应的短信服务提供商处注册账号并获取相应的API密钥等信息。

这些生成的代码是我借助当前特别火的chatGPT4.0生成的,

网站链接如下:

GPTicon-default.png?t=N7T8https://aiedu-super.cn/登录注册进去有5次免费使用机会,我是买了一年会员不限次数用下去的,给大家分享下这个东西,写代码,写文章真的很方便,有兴趣的注册进去可以看看。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/340104
推荐阅读
相关标签
  

闽ICP备14008679号