java发送手机短信验证码

第一步:首先得注册阿里云账号(没有阿里云账号的自己去注册一个)

第二步:开通服务 

         1. 搜索短信服务

       
 
 

        2.添加签名和模板(需要提交审核,审核通过后才可以使用,一般几分钟就可以出审核结果了)

           

 

 

第三步:编写测试代码

      1.打开帮助文档,找到SDK参考

      

     需要用什么语言写就点击安装什么的SDK,就行了

     

 

   我选择环境是推荐的是添加maven依赖

 java代码(复制调试代码进行修改就可以实现了)

package com.liusha.sendsms;
        import com.alibaba.fastjson.JSONObject;
        import com.aliyuncs.CommonRequest;
        import com.aliyuncs.CommonResponse;
        import com.aliyuncs.DefaultAcsClient;
        import com.aliyuncs.IAcsClient;
        import com.aliyuncs.exceptions.ClientException;
        import com.aliyuncs.exceptions.ServerException;
        import com.aliyuncs.http.MethodType;
        import com.aliyuncs.profile.DefaultProfile;
        import org.junit.jupiter.api.Test;
        import org.springframework.boot.test.context.SpringBootTest;

        import java.util.HashMap;

@SpringBootTest
class SendsmsApplicationTests {

    @Test
    void contextLoads() {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "填写你的AccessKey ID", "填写你的AccessKey Secret");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");  //不要改
        request.setSysVersion("2017-05-25");    //不要改
        request.setSysAction("SendSms");    //我选择sendSms
        //自定义的参数(手机号,验证码,签名,模板)
        request.putQueryParameter("PhoneNumbers", "发送到的手机号码");
        request.putQueryParameter("SignName", "你的签名名称");
        request.putQueryParameter("TemplateCode", "你的模版CODE");
        //构建一个短信验证码(一般都是传进来的随机数,我这里测试直接写死)
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",5588);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
        try {
            CommonResponse response = client.getCommonResponse(request);
            //输出响应是否成功
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

}  
运行结果

 

 

        

 

 

posted @ 2020-06-05 21:44  流—沙  阅读(671)  评论(0编辑  收藏  举报