需求
手机验证码短信发送
导入依赖,此处使用的阿里云的提供的短信服务,所需详细api见阿里云短信服务。
1 2 3 4 5 | <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version> 4.5 . 0 </version> </dependency> |
配置文件 ********.yml,在开通短信服务的页面按照帮助获取
1 2 3 4 5 6 7 8 | sms: accessKeyId: LTAI*********KAkB accessSecret: oK89*************zbUKJ3 SignName: DiuutWeb TemplateCode: SMS_******* 727 param: { "code" : "[value]" } # 如果显示param读取失败,把大括号替换成单引号 # param: '"code":"[value]"' |
SmsUtil工具类,使用时@Autowired引入即可自动注入调用并使用
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | /** * @Author Diuut * @Date 2020/4/7 12:25 */ @Component public class SmsUtil { @Value ( "${sms.accessKeyId}" ) private String accessKeyId; @Value ( "${sms.accessSecret}" ) private String accessKeySecret; @Value ( "${sms.SignName}" ) private String SignName; @Value ( "${sms.TemplateCode}" ) private String TemplateCode; @Value ( "${sms.param}" ) private String paramTemplate; public CommonResponse sendSms(String phone, String param) { DefaultProfile profile = DefaultProfile.getProfile( "cn-hangzhou" , accessKeyId, accessKeySecret); IAcsClient client = new DefaultAcsClient(profile); CommonRequest request = new CommonRequest(); //request.setProtocol(ProtocolType.HTTPS); request.setMethod(MethodType.POST); request.setDomain( "dysmsapi.aliyuncs.com" ); request.setVersion( "2017-05-25" ); request.setAction( "SendSms" ); request.putQueryParameter( "RegionId" , "cn-hangzhou" ); request.putQueryParameter( "PhoneNumbers" , phone); request.putQueryParameter( "SignName" , SignName); request.putQueryParameter( "TemplateCode" , TemplateCode); request.putQueryParameter( "TemplateParam" , paramTemplate.replace( "[value]" , param)); //上面如果大括号替换成了单引号,此处要在参数两头加上大括号。"{"+value+"}" try { CommonResponse response = client.getCommonResponse(request); // System.out.println(response.getData()); return response; } catch (ServerException e) { e.printStackTrace(); return null ; } catch (ClientException e) { e.printStackTrace(); return null ; } } } |