Java实现发送短信
学习视频地址:https://www.bilibili.com/video/av93808102
一.开通短信服务
1.百度搜索阿里大鱼
2.登录或注册(我是用支付宝登录的)
3.点击进入短信服务
点击短信服务
点击管理控制台
短信服务页面
4.查看帮助文档
帮助文档页面
获取私钥和密钥
点击进入阿里云短信服务文档使用指引
点击获取AccessKey(一定要保存好,而且不要给别人看)
快速入门界面
1)实名认证(没什么好说的)
2)开通短信服务
点击阿里云短信服务文档使用指引
点击开通短信服务
3)申请短信签名
添加签名(需要审核)
签名页面:
4)申请短信模板
添加短信模板(需要审核)
模板页面
5)发送短信
点击安装你需要的SDK(我用的是java SDK)
点击下载jar包,并导进项目中(还得导入一个gson.2.8.1.jar,有的版本不兼容)
或者使用maven(推荐)
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.1.0</version>
</dependency>
点击openAPI Explorer
输入左边的参数,自动生成右边的代码。将右边的代码复制到项目中。
5.注意事项
需要创建一个用户并授权(否则会报未授权的错误)
点击右边用户下面显示的访问控制,点击用户管理。新建一个用户(会审核一下)。
给新建的用户授予短信服务的权力:
需要充值一点钱(否则测试的时候会显示余额不足)。
6.验证码测试案例
前端代码(index.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>短信验证码系统</title>
<style type="text/css">
body{
background: #1f1f2b;
color: #fff;
}
.box{
width: 400px;
margin: 100px auto;
padding: 30px;
background: rgba(225,225,225,0.15);
box-shadow: 0px 0px 50px 0px #fff;
border-radius: 35px;
}
.context{
background: rgba(88,144,16,0.08);
height: 200px;
}
h3{
text-align: center;
}
.controller{
margin-top: 20px;
padding-left: 32px;
padding-top: 20px;
}
input{
background: none;
border: none;
border-bottom: 1px solid; #abaac2;
color: #fff;
}
a{
color: #dec4c4;
margin-left: 20px;
}
button {
text-align: center;
width: 100px;
font-size: 20px;
background: #87b5b3;
color: #fff;
border: none;
padding: 10px;
border-radius: 50px;
outline: none;
}
button:hover{
box-shadow: 0px 0px 5px 0px #fff;
}
</style>
</head>
<body>
<div class="box">
<h3>【里旗书城】短信验证码系统</h3>
<div class="context">
<div class="controller">
手机号码:<input type="text" id="phone">
</div>
<div class="controller">
<input type="text" id="code"><a href="javascript:void(0)" id="getCode">获取验证码</a>
</div>
<div class="controller">
<button style="text-align: center" onclick="validate()">校验</button>
</div>
</div>
</div>
<script type="text/javascript">
var obj = document.getElementById("getCode");
var flag = 60; //全局变量
obj.onclick=function(){
//控制时间
if(flag<60){
return;
}
//ajax
var xhr = new XMLHttpRequest();
xhr.open("get","getCode.do?phone="+document.getElementById("phone").value,true);//true:表示异步请求
//监控请求状态
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
//alert(xhr.responseText);
}
}
xhr.send(null);
timer();
}
function validate(){
//ajax
var xhr = new XMLHttpRequest();
xhr.open("get","validate.do?code="+document.getElementById("code").value,true);//true:表示异步请求
//监控请求状态
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
alert(xhr.responseText);
}
}
xhr.send(null);
}
//计时器
function timer(){
flag--;
obj.innerHTML=flag+"秒以后重新获取验证码"
if(flag==0){
obj.innerHTML="获取验证码";
flag=60;
}else{
setTimeout("timer()",1000);//递归
}
}
</script>
</body>
</html>
后端代码- GetCodeServlet(发送验证码并获取发送的验证码)
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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;
@WebServlet("/getCode.do")
public class GetCodeServlet extends HttpServlet {
@Override
public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
//生成一个思维数的随机验证码
String str = "";
for(int i = 0;i<4;i++) {
str+=(int)Math.floor(Math.random()*10);
}
request.getSession().setAttribute("_code", str);
//获取前台传送过来的手机号码
String phone = request.getParameter("phone");
sendMsg(phone, str);
}
private void sendMsg(String phone,String str) {
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FvTFDDuFoQuiybujgkq", "ZuXKnXoFeoz5MuIkF66hMNi3DDqwt9");
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", "SMS_186577188");
request.putQueryParameter("TemplateParam", "{'code':'"+str+"'}");
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
}
后端代码- ValidateServlet(验证码校验)
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/validate.do")
public class ValidateServlet extends HttpServlet {
@Override
public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
//1.获取前台传送过来的code
String code = request.getParameter("code");
//2.获取后台随机产生的验证码
String _code = (String) request.getSession().getAttribute("_code");
//3.对比是否相等
if(_code.equals(code)) {
System.out.println("成功!");
response.getWriter().print("success....");
}else {
response.getWriter().print("fail....");
}
}
}