阿里云API接口实现短信验证

阿里云API接口实现短信验证


项目所需要的jar包:
aliyun-java-sdk-core-4.1.0.jar
aliyun-java-sdk-dysmsapi-1.1.0.jar
gson-2.8.5.jar
jar包的下载地址:https://pan.baidu.com/s/1kyZDcd6rvp0SxPzMFrD35Q
提交码: s5c7

public class ShortMessage {
    static final String product = "Dysmsapi";
    static final String domain = "dysmsapi.aliyuncs.com";
    static final String accessKeyId = "你自己的accessKeyId ";
    static final String accessKeySecret = "你自己的accessKeySecret ";
    //调用阿里云接口对短信服务进行处理
    public static SendSmsResponse sendSms(String tel,String code) throws ClientException {
        //初始化acsClient
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //请求部分的组装
        SendSmsRequest request = new SendSmsRequest();
        //接收验证码的电话号码
        request.setPhoneNumbers(tel);
        //短信签名,必须在审核通过后再能使用
        request.setSignName("短信签名名称");
        //使用你在阿里云平台申请的“模板管理”中的短信模板名称
        request.setTemplateCode("模版CODE");
        //“\”代表转译
        //模版内容:您的动态码为:${code},您正在进行密码重置操作,如非本人操作,请忽略本短信
        request.setTemplateParam("{\"code\":"+code+"}");
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return sendSmsResponse;
    }
  }

查看自己accessKeyId 和accessKeySecret 的方法如下:
在这里插入图片描述
在这里插入图片描述
使用main方法进行测试,可以直接写在上面代码java类中

public static void main(String[] args) throws ClientException, InterruptedException {
	//随机生成一个6位数的整数作为验证码
	String code = String.valueOf((int)(Math.random()*9+1)*100000);
        //发短信
        SendSmsResponse response = sendSms("接收短信的电话号码",code);
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());
        Thread.sleep(3000L);
    }

API相关文档:
请求参数:
在这里插入图片描述
在这里插入图片描述
返回数据:
在这里插入图片描述
希望能够帮助到大家~~~~~~~~~~~~~~~~~~

发布了15 篇原创文章 · 获赞 10 · 访问量 583

猜你喜欢

转载自blog.csdn.net/weixin_44439445/article/details/102945634