java短信驗證

實現短信驗證,需要第三方平臺,

接下來我們用網易雲來實現,

先到官網上註冊,得到id,key,官網上都有實例,

package com.yinhe.utils;  
  
import java.security.MessageDigest;  
import java.util.ArrayList;  
import java.util.Date;  
import java.util.List;  
  
import org.apache.http.HttpRequest;  
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.DefaultHttpClient;  
import org.apache.http.message.BasicNameValuePair;  
import org.apache.http.util.EntityUtils;  
  
/**  
 * 發送驗證碼  
 * @author liuxuanlin  
 *  
 */  
public class MessageUtils {  
    //發送驗證碼的請求路徑URL  
    private static final String  
            SERVER_URL="https://api.netease.im/sms/sendcode.action";  
    //網易雲信分配的賬號,請替換你在管理後臺應用下申請的Appkey  
    private static final String   
            APP_KEY="9c8544*************c6a80";  
    //網易雲信分配的密鑰,請替換你在管理後臺應用下申請的appSecret  
    private static final String APP_SECRET="03d****ade";  
    //隨機數  
    private static final String NONCE="0123456789";  
    //短信模板ID  
    private static final String TEMPLATEID="3119013";  
     
    //驗證碼長度,範圍4~10,默認爲4  
    private static final String CODELEN="6";  
  
    public static String sendMessage(String phone) throws Exception {  
         //手機號  
        String MOBILE=phone;  
        DefaultHttpClient httpClient = new DefaultHttpClient();  
        HttpPost httpPost = new HttpPost(SERVER_URL);  
        String curTime = String.valueOf((new Date()).getTime() / 1000L);  
        /*  
         * 參考計算CheckSum的java代碼,在上述文檔的參數列表中,有CheckSum的計算文檔示例  
         */  
        String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);  
  
        // 設置請求的header  
        httpPost.addHeader("AppKey", APP_KEY);  
        httpPost.addHeader("Nonce", NONCE);  
        httpPost.addHeader("CurTime", curTime);  
        httpPost.addHeader("CheckSum", checkSum);  
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");  
  
        // 設置請求的的參數,requestBody參數  
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
        /*  
         * 1.如果是模板短信,請注意參數mobile是有s的,詳細參數配置請參考“發送模板短信文檔”  
         * 2.參數格式是jsonArray的格式,例如 "['13888888888','13666666666']"  
         * 3.params是根據你模板裏面有幾個參數,那裏面的參數也是jsonArray格式  
         */  
        nvps.add(new BasicNameValuePair("templateid", TEMPLATEID));  
        nvps.add(new BasicNameValuePair("mobile", MOBILE));  
        nvps.add(new BasicNameValuePair("codeLen", CODELEN));  
  
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));  
  
        // 執行請求  
        HttpResponse response = httpClient.execute(httpPost);  
        /*  
         * 1.打印執行結果,打印結果一般會200、315、403、404、413、414、500  
         * 2.具體的code有問題的可以參考官網的Code狀態表  
         */  
          
        return EntityUtils.toString(response.getEntity(), "utf-8");    
    }  
      
}  
class CheckSumBuilder {  
    // 計算並獲取CheckSum  
    public static String getCheckSum(String appSecret, String nonce, String curTime) {  
        return encode("sha1", appSecret + nonce + curTime);  
    }  
  
    // 計算並獲取md5值  
    public static String getMD5(String requestBody) {  
        return encode("md5",requestBody);  
    }  
  
    private static String encode(String algorithm, String value) {  
        if (value == null) {  
            return null;  
        }  
        try {  
            MessageDigest messageDigest  
                    = MessageDigest.getInstance(algorithm);  
            messageDigest.update(value.getBytes());  
            return getFormattedText(messageDigest.digest());  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
    private static String getFormattedText(byte[] bytes) {  
        int len = bytes.length;  
        StringBuilder buf = new StringBuilder(len * 2);  
        for (int j = 0; j < len; j++) {  
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);  
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);  
        }  
        return buf.toString();  
    }  
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',  
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };  
}  



[html] view plain copy
package com.yinhe.web.servlet;  
  
import java.io.IOException;  
import java.io.PrintWriter;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import com.alibaba.fastjson.JSON;  
import com.alibaba.fastjson.JSONObject;  
import com.yinhe.utils.MessageUtils;  
  
public class MessageServlet extends BaseServlet {  
    public void hqyzm(HttpServletRequest req,HttpServletResponse resp) throws Exception {  
        //MessageUtils.sendMsg(req.getParameter("phone"), req.getParameter("yanz"));  
        String phone=req.getParameter("phone");  
        String  me=MessageUtils.sendMessage(phone);  
        System.out.println(me);  
        JSONObject jsonObject= (JSONObject) JSON.parse(me);  
        String obj = jsonObject.getString("obj");    
        req.getSession().setAttribute("code", obj);  
        System.out.println(obj);  
        resp.setContentType("text/html;charset=UTF-8");  
        boolean result=false;  
        if(phone!=null){  
            result=true;  
        }  
        String jsonString = "{'result':"+result+"}";  
        resp.getWriter().println(jsonString);  
    }  
public void yz(HttpServletRequest req,HttpServletResponse resp) {  
      String  p=req.getParameter("yanz");  
      System.out.println(p);  
      System.out.println(req.getSession().getAttribute("code"));  
        if(p.equals(req.getSession().getAttribute("code"))){  
            try {  
                resp.setContentType("text/html;charset=UTF-8");  
                resp.getWriter()  
                .println(  
                        "<script>confirm('驗證碼正確!');location.href='/ShopStore/duanxin.jsp?';</script>");  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }else {  
            try {  
                resp.setContentType("text/html;charset=UTF-8");  
                resp.getWriter()  
                .println(  
                        "<script>confirm('驗證碼錯誤');location.href='/ShopStore/duanxin.jsp?';</script>");  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
}  
}  

[java] view plain copy
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
      
    <title>My JSP 'duanxin.jsp' starting page</title>  
      
    <meta http-equiv="pragma" content="no-cache">  
  </head>  
<script src="js/jquery.js" type="text/javascript"></script>  
<script src="js/jquery.validate.js" type="text/javascript"></script>  
  <style type="text/css">  
</style>  
<style type="text/css">  
label.error {  
   COLOR: red;  
}  
</style>  
<script type="text/javascript">  
 jQuery.validator.addMethod("checka",function(value){  
      var reg=/^[0-9_]{11}$/;  
      return reg.test(value);  
  },"輸入格式有誤,請輸入11位有效的手機號碼!");  
    $(document).ready(function() {  
        jQuery("#regForm").validate({  
            rules : {  
                "phone" : {  
                    required : true,  
                    checka:true  
                }  
                ,"yanz" : {  
                    required : true  
                }  
            },  
            messages : {  
                "phone" : {  
                    required : "手機號不能爲空",  
                }  
                ,"yanz" : {  
                    required : "請輸入驗證碼"  
                }  
                  
            },  
            errorElement : "label",  
            highlight : function(element, errorClass)//針對驗證的表單添加高亮顯示  
            {  
                $(element).addClass(errorClass);  
            },  
            success : function(label) {  
                label.html("").addClass("valid");  
            }  
  
        })  
  
    })  
</script>  
<script type="text/javascript">  
    function check(){  
        $.ajax({  
            url:"${pageContext.request.contextPath}/duanxin?method=hqyzm",  
            data:{"phone":$("#myphone").val()},  
            dataType:"json",  
            type:"post",  
            //true 異步  
            //false 同步  
            async:false,  
            success:function(data){  
            if(!data.result){  
                    alert("驗證碼發送失敗");  
                }else{  
                    alert("驗證碼已發送,請注意查收");  
                }  
            }  
        });  
    }  
</script>  
  <body>  
  <form action="${pageContext.request.contextPath}/duanxin?method=yz" method="post"  id="regForm">  
    請輸入手機號:<input type="text" name="phone" value="${phone}"  id="myphone"><br>  
    驗     證     碼:<input type="text" name="yanz" value="">  <input type="button" onclick="check()" value="點擊獲取驗證碼"></input><br>  
    <input type="submit">  
    </form>  
  </body>  
</html>  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章