获取短信验证码(阿里云)进行验证

首先需要去阿里云网站申请短信模板(根据网站的新手引导进行注册验证),注册成功后,需要引入依赖或者jar包,然后进行编写代码

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.1.0</version>
</dependency>

系统产生随机位数的验证码(位数根据传来值length进行产生多少位的验证码)

public String randomNumber(int length){
		if(length<1){
			return "";
		}
		String[] arr={"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
	    StringBuffer bufString=new StringBuffer();
		for(int i=0;i<length;i++){
			bufString.append(arr[(int)Math.round(Math.random() * arr.length)]);
	    }
	    return bufString.toString();
	 
	}

发送短信验证码的方法:

private void sendMsg(String phone,String code){
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "阿里云用户的AccessKey ID", "阿里云用户的Access Key Secret");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        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", "签名名称");
        request.putQueryParameter("TemplateCode", "模版CODE");
        request.putQueryParameter("TemplateParam", "{'code':"+code+"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
		
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值