链接:https://pan.baidu.com/s/1saRmzciNQWpFxHJRN0ISTg 密码:siyt
实现发送验证码的工程下载
1、我们打开这个工程,查看其中的代码
package com.ghj.test;
import java.io.IOException;
import java.util.Scanner;
import com.ghj.tool.SMSUtils;
/**
* 测试验证码类短信
*/
public class CaptchaMsgTest {
private static String mobile = "xxxxxxxxxxxx";
/**
* 短信内容:您的验证码为%s,10分钟内有效。
*/
@SuppressWarnings("resource")
public static void main(String[] args) {
if(SMSUtils.isMobile(mobile)){
try {
SMSUtils.sendCode(mobile,"3943633");//发送验证码
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.print("请输入您收到的短信验证码:");
String code = new Scanner(System.in).next();
try {
if(SMSUtils.verifyCode(mobile, code)){//校验验证码
System.out.println("验证码正确...");
}else{
System.out.println("验证码错误...");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
mobile属性可以改为你想要发送到的手机号码 sendCode方法中的第二个参数为验证码模板id 其中调用了smsutil中的sendcode方法来向手机发送验证码
package com.ghj.tool;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 短信相关的工具类
*/
public class SMSUtils {
private static final String NONCE = "123456";
private static final String APP_SECRET = "87ae5a14b7e3";
private static final String APP_KEY = "c5e7dd7648b871180f53063cf1d3f869";
/**
* 检测手机号有效性
*
* @param mobile 手机号码
* @return 是否有效
*/
public static final boolean isMobile(String mobile){
Pattern pattern = Pattern.compile("^((1[3578][0-9])|(14[57]))\\d{8}$");
Matcher matcher = pattern.matcher(mobile);
return matcher.matches();
}
/**
* 验证码类短信,注意:该短信中验证码不能自己生成,由网易云帮我们生成
*
* @param mobile 手机号码
* @param templateId 验证码模板ID
* @return 是否发送成功
*/
public static final boolean sendCode(String mobile, String templateId) throws IOException {
HttpPost httpPost = new HttpPost("https://api.netease.im/sms/sendcode.action");
String currentTime = String.valueOf(new Date().getTime()/1000L);
String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,currentTime);
//set header
httpPost.setHeader("AppKey",APP_KEY);
httpPost.setHeader("CurTime",currentTime);
httpPost.setHeader("Nonce",NONCE);
httpPost.setHeader("CheckSum",checkSum);
httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
//set data
List nameValuePairList = new ArrayList();
nameValuePairList.add(new BasicNameValuePair("mobile",mobile));
nameValuePairList.add(new BasicNameValuePair("templateid", templateId));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList,"utf-8"));
//start request
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
String responseResult = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
System.out.println("responseResult:"+responseResult);
String stateCode = JSON.parseObject(responseResult).getString("code");
if(stateCode.equals("200")){
return true;
}
return false;
}
/**
* 判断用户输入验证码与网易云生成的验证码是否一致
*
* @param mobile 电话号码
* @param code 发送到mobile上的短信
*/
public static final boolean verifyCode(String mobile, String code) throws IOException {
HttpPost httpPost = new HttpPost("https://api.netease.im/sms/verifycode.action");
String currentTime = String.valueOf(new Date().getTime()/1000L);
String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,currentTime);
//set header
httpPost.setHeader("AppKey",APP_KEY);
httpPost.setHeader("CurTime",currentTime);
httpPost.setHeader("Nonce",NONCE);
httpPost.setHeader("CheckSum",checkSum);
httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
//set data
List nameValuePairList = new ArrayList();
nameValuePairList.add(new BasicNameValuePair("code",code));
nameValuePairList.add(new BasicNameValuePair("mobile",mobile));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList,"utf-8"));
//start request
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
String responseResult = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
System.out.println("responseResult:"+responseResult);
String stateCode = JSON.parseObject(responseResult).getString("code");
if(stateCode.equals("200")){
return true;
}
return false;
}
}
因为我们是通过网易的第三方验证码服务来实现,所以其中app_key和app_secret两个属性的值需要网易云提供
http://netease.im/sms 我们登陆这个网站 注册账户并登陆
创建应用,创建完成后,在下面未开通的服务中找到短信并申请免费试用,在最上方找到appkey管理,点进去后就有app key和app secret,将这两个值复制到smsutil类中的属性,点击短信管理模板跳转后在点击验证码模板可以自定义短信格式,每个验证码模板都有对应的id,选择一个复制到第一个程序sendCode方法的第二个参数中。
此时运行上面的第一个程序,手机就能收到验证码了。
2、下面我们通过验证码来实现网页登陆功能
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
用户登陆
这是登陆页面jsp的代码,其中有两个函数,分别来实现发送验证码和校验验证码
package com.xt.userinfo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xt.send_checkcode.tool.SMSUtils;
/**
* Servlet implementation class CheckServlet
*/
public class SendcodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String mobile = request.getParameter("phonenumber");
System.out.println(mobile);
if(SMSUtils.isMobile(mobile)){
try {
SMSUtils.sendCode(mobile,"3953566");//发送验证码
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这是实现发送验证码的servlet,它获取到了登陆页面上的手机号,并调用smsutils中的sendCode方法将手机号传入,这样就能将验证码发送到手机了。
package com.xt.userinfo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xt.send_checkcode.tool.SMSUtils;
/**
* Servlet implementation class CheckcodeServlet
*/
public class CheckcodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String code = request.getParameter("checkword");
String mobile = request.getParameter("phonenumber");
System.out.println(mobile);
System.out.println(code);
if(SMSUtils.verifyCode(mobile, code)) {
System.out.println("success");
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else {
System.out.println("fail");
request.getRequestDispatcher("/fail.jsp").forward(request, response);
}
}
}
这是实现验证并登陆的servlet,它获取到页面上的手机号和你刚刚收到并输入的验证码,再调用smsutils中的verify方法并将这两个参数传入,如果返回true就会登陆成功