java阿里短信接口调用
阿里短信接口调用
- 导入依赖
<!-- 登陆短信需要用的jar包 -->
<dependency> <groupId>com.aliyun.mns</groupId> <artifactId>aliyun-sdk-mns</artifactId> <version>1.1.8</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore-nio --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore-nio</artifactId> <version>4.4.10</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.10</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpasyncclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpasyncclient</artifactId> <version>4.1.4</version> </dependency>
<!-- gao阿里短信 --> <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core --> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>3.3.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-dysmsapi --> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-dysmsapi</artifactId> <version>1.0.0</version> </dependency> |
- 登陆阿里云
创建用户key等内容
https://help.aliyun.com/document_detail/59210.html?spm=a2c4g.11174283.4.1.meieQd
该步骤一步一步的创建
- 创建 工具类/Controller类
工具类 |
package com.cpic.caf.user.LoginController;
import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest; import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.dysmsapi.transform.v20170525.SendSmsResponseUnmarshaller; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.HttpResponse; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile;
import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID;
/** * author * * Created on 18/8/8. * 短信API产品的DEMO程序 * 执行main函数即可体验短信产品API功能(只需要将AK替换成开通了云通信-短信产品功能的AK即可) * 工程依赖了2个jar包(存放在工程的libs目录下) * 1:aliyun-java-sdk-core.jar * 2:aliyun-java-sdk-dysmsapi.jar * * 备注:Demo工程编码采用UTF-8 * 国际短信发送请勿参照此DEMO */ public class SmsDemoToolsCxl {
//产品名称:云通信短信API产品,开发者无需替换 static final String product = "Dysmsapi"; //产品域名,开发者无需替换 static final String domain = "dysmsapi.aliyuncs.com";
// TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找) static final String accessKeyId = "accessKeyId "; static final String accessKeySecret = "accessKeySecret ";
public static SendSmsResponse sendSms(String phoneNumber,String content) throws ClientException {
//可自助调整超时时间 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暂不支持region化 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(phoneNumber); //必填:短信签名-可在短信控制台中找到 request.setSignName("喜事码头"); //必填:短信模板-可在短信控制台中找到 request.setTemplateCode("SMS_141890017"); //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 request.setTemplateParam("{\"code\":\""+content+"\"}");
//选填-上行短信扩展码(无特殊需求用户请忽略此字段) //request.setSmsUpExtendCode("90997");
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 request.setOutId("yourOutId");
//hint 此处可能会抛出异常,注意catch SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
return sendSmsResponse; }
public static QuerySendDetailsResponse querySendDetails(String bizId) throws ClientException {
//可自助调整超时时间 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暂不支持region化 IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象 QuerySendDetailsRequest request = new QuerySendDetailsRequest(); //必填-号码 request.setPhoneNumber("15000000000"); //可选-流水号 request.setBizId(bizId); //必填-发送日期 支持30天内记录查询,格式yyyyMMdd SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd"); request.setSendDate(ft.format(new Date())); //必填-页大小 request.setPageSize(10L); //必填-当前页码从1开始计数 request.setCurrentPage(1L);
//hint 此处可能会抛出异常,注意catch QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);
return querySendDetailsResponse; }
/** * 随机生成code * @return */ public static String cod(){ String codd=""; for(int i=0;i<4;i++){ String code="123456789qwertyuipasdfghjklzxcvbnmQWERTYUIPASDGFHJKLZXCVBNM";//59个 char co=code.charAt((int)(Math.random()*58));//通过使用Math.random()函数产生随机数, //charAt(int i)返回对应的下标字符 //再通过*58(排除o,O,0干扰后),强制转换为int类型 codd+=String.valueOf(co);//将产生的随机字符传入字符串codd } return codd; }
} |
Controller类 |
package com.cpic.caf.user.LoginController;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.exceptions.ClientException; import com.cpic.caf.workers.hall.service.LoginService;
@Controller @RequestMapping("/login") public class LoginCoreController {
@Autowired private LoginService loginService;
/** * 跳转到登陆页面 * @return */ @RequestMapping("/index.html") public String toLoginIndex(){ return "user/login"; }
@RequestMapping(value="/workuser",method=RequestMethod.POST) @ResponseBody public String workUserLogin(@RequestParam("user_code")String user_code, @RequestParam("user_psw")String user_psw){
Boolean flag = loginService.WorkUserLogin(user_code, user_psw); if (flag) { return "true"; }else { return "false"; } }
@RequestMapping(value="/getCode") @ResponseBody public String takeloginCode(@RequestParam("phone")String phone) throws ClientException, InterruptedException{
//发短信 String code = SmsDemoToolsCxl.cod(); SendSmsResponse response = SmsDemoToolsCxl.sendSms(phone,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);
//查明细 if(response.getCode() != null && response.getCode().equals("OK")) { QuerySendDetailsResponse querySendDetailsResponse = SmsDemoToolsCxl.querySendDetails(response.getBizId()); System.out.println("短信明细查询接口返回数据----------------"); System.out.println("Code=" + querySendDetailsResponse.getCode()); System.out.println("Message=" + querySendDetailsResponse.getMessage()); int i = 0; for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs()) { System.out.println("SmsSendDetailDTO["+i+"]:"); System.out.println("Content=" + smsSendDetailDTO.getContent()); System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode()); System.out.println("OutId=" + smsSendDetailDTO.getOutId()); System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum()); System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate()); System.out.println("SendDate=" + smsSendDetailDTO.getSendDate()); System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus()); System.out.println("Template=" + smsSendDetailDTO.getTemplateCode()); } System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount()); System.out.println("RequestId=" + querySendDetailsResponse.getRequestId()); } return code; }
}
|
- 前端页面实现
表单 |
<li>
<input class="code" type="text" required="required" id="codeInput" placeholder="">
<button class="code fr" id="getCode">获取验证码</button>
<input type="hidden" value="<%=request.getContextPath()%>" id="path"> <input type="hidden" value="" id="code">
</li> |
JS部分 |
<script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script> |
Ajax向后台获得验证码(60秒时间限制) |
$("#getCode").click(function(){ var path = $("#path").val(); var phone = $("#phone").val(); $.ajax({ url : path + "/login/getCode", type : "post", dataType : "text", data : { "phone":$("#phone").val() }, success :function(data){ $("#code").val(data);//设置隐藏域 var mydate= new Date();//获取当前时间 mydate.setMinutes(mydate.getMinutes()+1); //当前时间加1分钟 var end_time = new Date(mydate).getTime(); //月份是实际月份-1 var sys_second = (end_time-new Date().getTime())/1000; var timer = setInterval(function(){ if (sys_second > 1) { sys_second -= 1; var second = Math.floor(sys_second % 60); $("#getCode").attr("disabled","true");//添加disabled属性 $("#btn_code").css("color","gray"); $("#getCode").html(second+"s后重新获取验证码"); } else { $("#getCode").removeAttr("disabled");//移除disabled属性 $("#getCode").css("color","black"); $("#getCode").html("获取验证码"); clearInterval(timer);//清楚定时器 } }, 1000); } });//ajax }); |
- 工具类参数指定
改成提供的内容
AccessId和Key即可,阿里云短信后台都有提供
- 项目签名,一般是中文
- 短信模板,可以自己定义
- 模板变量,为json,具体限制在阿里后台有说明
- 工具类方法解说
方法名称 |
方法作用 |
注意事项 |
|
sendSms(String, String) |
发送短信 |
需要修改上面的几个变量 |
|
querySendDetails(String) |
配置短信 |
不需要修改 |
|
cod() |
生成随机4位(可调)验证码 |
静态直接调用 |
|