使用聚合数据短信API测试(短信验证登录)

搞一手聚合数据短信API测试(之前用阿里云的搞过,今天我们用聚合)

  1. 注册聚合账号!聚合官网链接

  2. 登陆后进入短信服务API(免费提供十次)
    使用聚合数据短信API测试(短信验证登录)_第1张图片

  3. 添加自定义模板(审核速度看脸)
    使用聚合数据短信API测试(短信验证登录)_第2张图片
    使用聚合数据短信API测试(短信验证登录)_第3张图片

  4. 审核成功后得到模板ID
    使用聚合数据短信API测试(短信验证登录)_第4张图片
  5. 之后得到AppKey进入java测试
    使用聚合数据短信API测试(短信验证登录)_第5张图片

下面我们写Java代码

调用短信接口类 : SMSCode.java

package com.SMSverification;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * 调用短信接口类
 * @author sunsetRain
 *
 */
public class SMScode {

    //把手机号码和随机验证码传递过来
    public static boolean sendCode(String phoneNumber, String code) throws Exception {

        String str_code = URLEncoder.encode("#code#=" + code, "UTF-8");
        //包装好URL对象,将接口地址包装在此对象中
        URL url = new URL("http://v.juhe.cn/sms/send?mobile=" + phoneNumber +
                "&tpl_id=101810&tpl_value=" + str_code + "&key=8cc630d8a9c4d0914fad9937dff91bf9");
                /* 短信模板id */                            /* 短信应用接口的key */
        //打开连接,得到连接对象
        URLConnection connection = url.openConnection();
        //向服务器发送连接请求
        connection.connect();
        //获得服务器响应的数据
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        StringBuffer buffer = new StringBuffer();
        String lineDate = null;
        while((lineDate = bufferedReader.readLine()) != null) {
            buffer.append(lineDate);
        }
        bufferedReader.close();
        if(buffer.toString().indexOf("\"error_code\":0")>=0 ) {
            return true;
        }

        return false;
    }


}

随机生成验证码类sendCodeServlet.java

package com.SMSverification;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.regex.Pattern;

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("/code")
public class sendCodeServlet extends HttpServlet {

    private static final long serialVersionUID = -8559217512617151073L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String phoneNumber = req.getParameter("phoneNumber");
        System.out.println("手机号码:" + phoneNumber);

        if(phoneNumber.trim().equals("") || phoneNumber == null) {
            System.out.println("手机号码为空!");
            resp.sendRedirect("index.jsp");
            return ;
        }
        //手机号码格式判断
        if(!Pattern.matches("^1[3|4|5|7|8]\\d{9}$", phoneNumber)) {
            System.out.println("手机格式错误!");
            resp.sendRedirect("index.jsp");
            return ;
        }
        //生成一个60~9之间的随机字符串
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            buffer.append(random.nextInt(10));
        }

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        try {
            if(!SMScode.sendCode(phoneNumber, buffer.toString())) {
                out.println("验证码发送失败!");
            } else {
                //将验证码、手机号码和当前的系统时间存储到session中
                req.getSession().setAttribute("code", buffer.toString());
                req.getSession().setAttribute("number", phoneNumber );
                req.getSession().setAttribute("time", System.currentTimeMillis());
                out.println("验证码发送成功!");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        out.close();
    }

}

后台验证短信验证码处理类LoginServlet.java

package com.SMSverification;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/login")
public class LoginServlet extends HttpServlet{

    private static final long serialVersionUID = 6610029513343828205L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        req.setCharacterEncoding("utf-8");
        String phoneNumber = req.getParameter("phoneNumber");
        String code = req.getParameter("code");

        if(phoneNumber == null || phoneNumber.trim().equals("") || code.trim().equals("")) {
            System.out.println("手机号码或验证码为空!");
            resp.sendRedirect("idnex.jsp");
            return ;
        }

        if(!Pattern.matches("^1[3|4|5|7|8]\\d{9}$", phoneNumber)) {
            System.out.println("手机号码格式错误!");
            resp.sendRedirect("index.jsp");
            return ;
        }

        //从session中拿出数据
        HttpSession session = req.getSession();
        String code_session = (String)session.getAttribute("code");
        String number = (String)session.getAttribute("number");
        Long time = (Long)session.getAttribute("time");
        //清除session中的数据
        session.removeAttribute("code");
        session.removeAttribute("number");
        session.removeAttribute("time");

        if(code_session == null || code_session.trim().equals("")) {
            System.out.println("验证码为空!");
            resp.sendRedirect("index.jsp");
            return ;
        }
        //验证码登录时效10分钟
        if((System.currentTimeMillis() - time) / 1000 / 60 >= 0) {
            System.out.println("验证码已过期!");
            resp.sendRedirect("index.jsp");
            return ;
        }
        //发送验证码的手机号码和登录时得到手机号码必须一致
        if(!number.trim().equalsIgnoreCase(phoneNumber)) {
            System.out.println("手机号码不一致!");
            resp.sendRedirect("index.jsp");
            return ;
        }

        if(code_session.trim().equalsIgnoreCase(code)) {
            System.out.println("登录成功!");
            resp.addHeader("Content-Type", "text/html;charset=GBK");
            PrintWriter printWriter = resp.getWriter();
            printWriter.println("");
            printWriter.close();
        } else {
            System.out.println("验证码不一致!");
            resp.sendRedirect("index.jsp");
            return ;
        }




    }


}

测试页面index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=IOS-8859-1">
<title>Insert title heretitle>
head>

    <script type="text/javascript">
        function sendCode() {
            var number = window.document.getElementById("phoneNumber").value;
            window.open("code?phoneNumber=" + number);
            window.alert('发送验证码');
        }

    script>

<body>

    <form action="SystemManage.jsp" method="post">
        <input type="text" id="phoneNumber" name="phoneNumber" placeholder="手机号码" pattern="^1[3|4|5|7|8]\d{9}$" required="required" >
        <br><br>
        <input type="text" name="code" placeholder="验证码" required="required" >
        <button type="button" onclick="sendCode()">发送验证码button>
        <br><br>
        <button type="submit">登录button>
    form>

body>
html>

效果图:
使用聚合数据短信API测试(短信验证登录)_第6张图片

使用聚合数据短信API测试(短信验证登录)_第7张图片

使用聚合数据短信API测试(短信验证登录)_第8张图片

你可能感兴趣的:(滴滴)