短信驗證碼實現

一、leftTime倒計時插件

下載leftTime插件:https://download.csdn.net/download/zyx1260168395/12062695

使用的是這個樣式:http://www.jq22.com/yanshi15974

主要的參數:

$.leftTime(60,function(d){
	//d.status,值true||false,倒計時是否結束;
	//d.s,倒計時秒;
});

例子:

//短信發送成功,開始倒計時
//判斷按鈕有沒有變灰,如果變灰就不觸發該事件了,這裏變灰的樣式是"on"
if(!$("#messageCodeBtn").hasClass("on"){
	$.leftTime(60,function (d) {
		if (d.status) {
			$("#messageCodeBtn").addClass("on");
			$("#messageCodeBtn").html((d.s == "00" ? "60" : d.s) + "s後獲取");
	
		} else {
			$("#messageCodeBtn").removeClass("on");
			$("#messageCodeBtn").html("獲取驗證碼");
		}
	})
}

二、解析JSON

1. 添加依賴

使用fastJson

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.36</version>
</dependency>

2. 解析json字符串

  • 將json字符串轉換爲對象:

    JSONObject jsonObject = JSONObject.parseObject(json)
    
  • 獲取值(方法名:get+數據類型),如獲取String:

    jsonObject.getString(key);
    

三、解析xml

解析XML方式有兩種

  1. SAX解析:邊讀邊解析,只能讀
  2. Dom解析:一次性將解析的內容加載內存,不僅能讀,還能對文檔的節點進行增刪改

1. 添加依賴

常用的解析方式:Dom4j + xpath

解析該方式需要引入依賴:jaxen.jar,該jar包是支持xpath語法的jar包,dom4j默認是依賴jaxen.jar的,所以在maven中,只需引入dom4j依賴即可

<dependency>
    <groupId>org.dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>2.1.0</version>
</dependency>

2. xPath語法

https://www.w3school.com.cn/xpath/xpath_syntax.asp

3. java中使用xPath解析xml

  • Document dom = DocumentHelper.parseText(xmlStr):將xml字符串轉換爲DOM對象
  • Element element = (Element) dom.selectSingleNode(titleXpath);:通過xPath字符串選擇出元素,多個節點使用selectNodes()方法,返回List集合
  • element.getText():獲取文本內容
  • element.attributeValue(屬性名):獲取屬性值

四、HttpClient

1. 相關依賴

<!-- httpclient4.5版本 -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

<!-- httpclient3.1版本 -->
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

2. jdk實現httpclient

使用java.net包獲取遠程url數據、調用遠程接口

一般分爲兩個方法, doGet() 和doPost(),因爲兩個請求方法對參數的處理方法不同

  • doGet()關鍵步驟:
    • 通過URL創建一個遠程連接對象
    • 通過連接對象打開連接,並設置請求參數(連接方式、連接超時時間、響應超時時間)
    • 通過連接對象獲取響應參數的輸入流,並將輸入流轉換成字符串
    • 關閉資源
  • doPost()關鍵步驟:
    • 通過URL創建一個遠程連接對象
    • 通過連接對象打開連接,並設置請求參數(連接方式、連接超時時間、響應超時時間、打開讀寫數據)
    • 通過連接對象創建一個輸出流,將請求參數傳出去
    • 通過連接對象獲取響應參數的輸入流,並將輸入流轉換成字符串
    • 關閉資源
package com.bjpowernode.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * java原生httpclient
 * Description:使用java.net包獲取遠程url數據、調用遠程接口
 */
public class HttpClientTest01 {

    /**
     * GET請求
     *
     * @param httpUrl
     * @return
     */
    public static String doGet(String httpUrl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;//返回結果字符串

        try {
            //創建遠程url連接對象
            URL url = new URL(httpUrl);
            //通過遠程url連接對象打開一個連接,強轉成httpURLConnection類
            connection = (HttpURLConnection) url.openConnection();
            //設置連接方式:get
            connection.setRequestMethod("GET");
            //設置連接主機服務器的超時時間:15000毫秒
            connection.setConnectTimeout(15000);
            //設置讀取遠程返回的數據時間:60000毫秒
            connection.setReadTimeout(60000);

            //通過connection連接,獲取輸入流
            is = connection.getInputStream();
            //封裝輸入流is,並指定字符集
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			
            //存放數據
            StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp);
                sbf.append("\r\n");//回車+換行
            }

            result = sbf.toString();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //關閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();//關閉遠程連接
        }

        return result;
    }


    /**
     * POST 請求
     *
     * @param httpUrl
     * @param param
     * @return
     */
    public static String doPost(String httpUrl, String param) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;

        try {
            //創建遠程url連接對象
            URL url = new URL(httpUrl);
            //通過遠程url連接對象打開連接
            connection = (HttpURLConnection) url.openConnection();
            //設置連接請求方式
            connection.setRequestMethod("POST");
            //設置連接主機服務器超時時間:15000毫秒
            connection.setConnectTimeout(15000);
            //設置讀取主機服務器返回數據超時時間:60000毫秒
            connection.setReadTimeout(60000);

            //默認值爲:false,當向遠程服務器傳送數據/寫數據時,需要設置爲true
            connection.setDoOutput(true);
            //默認值爲:true,當前向遠程服務讀取數據時,設置爲true,該參數可有可無
            connection.setDoInput(true);

            //通過連接對象獲取一個輸出流
            os = connection.getOutputStream();
            //通過輸出流對象將參數寫出去/傳輸出去,它是通過字節數組寫出的
            os.write(param.getBytes());//把需要傳送的參數發送給遠程url

            //通過連接對象獲取一個輸入流,向遠程讀取
            is = connection.getInputStream();
            //對輸入流對象進行包裝
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            StringBuffer sbf = new StringBuffer();
            String temp = null;
            //循環遍歷一行一行讀取數據
            while ((temp = br.readLine()) != null) {
                sbf.append(temp);
                sbf.append("\r\n");
            }

            result = sbf.toString();


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //關閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //斷開與遠程地址url的連接
            connection.disconnect();
        }
        return result;
    }
}

3. 使用httpclient3.1版本

doGet()關鍵步驟:

  • 創建 httpClient 對象
  • 創建Get方法實例對象 GetMethod,並設置請求參數(請求方法、超時時間)
  • 發送請求,然後判斷狀態碼,如果是200的話就通過 GetMethod 對象獲取輸入流,並轉換爲字符串
  • 關閉流,釋放資源
    doPost()關鍵步驟:
  • 創建 httpClient 對象
  • 創建Post方法實例對象 PostMethod,並設置請求參數(請求方法、超時時間)
  • 將參數存入請求體中(使用數組,數組中的元素是鍵值對,鍵是參數名,值是二進制數據)
  • 發送請求,判斷狀態碼,如果是200的話就通過 GetMethod 對象獲取輸入流,並轉換爲字符串
  • 關閉流,釋放資源
package com.bjpowernode.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 * HttpClient3.1 是apache下操作遠程 url的工具包
 * 雖然已不再更新,但實現工作中使用httpClient3.1的代碼還是很多
 * 現仍然在大量使用
 */
public class HttpClientTest02 {


    /**
     * GET 請求方法
     * 注:如果需要傳遞參數,把參數拼接在url地址後面
     */
    public static String doGet(String url) {
        //輸入流
        InputStream is = null;
        BufferedReader br = null;
        String result = null;

        //創建httpClient實例
        HttpClient httpClient = new HttpClient();

        //設置http連接主機服務超時時間:15000毫秒
        //先獲取連接管理器對象,再獲取參數對象,再進行參數的賦值
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);

        //創建一個Get方法實例對象
        GetMethod getMethod = new GetMethod(url);
        //設置get請求超時爲60000毫秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        //設置請求重試機制,默認重試次數:3次,參數設置爲true,重試機制可用,false相反
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, true));


        try {
            //執行Get方法
            int statusCode = httpClient.executeMethod(getMethod);
            //判斷返回碼
            if (statusCode != HttpStatus.SC_OK) {
                //如果狀態碼返回的不是ok,說明失敗了,打印錯誤信息
                System.err.println("Method faild: " + getMethod.getStatusLine());
            }

            //通過getMethod實例,獲取遠程的一個輸入流
            is = getMethod.getResponseBodyAsStream();
            //包裝輸入流
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            StringBuffer sbf = new StringBuffer();
            //讀取封裝的輸入流
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp).append("\r\n");
            }

            result = sbf.toString();

        } catch (Exception e) {
            System.err.println("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } finally {
            //關閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //釋放連接
            getMethod.releaseConnection();
        }

        return result;
    }

    /**
     * POST 請求方法
     *
     * @param url
     * @param paramMap
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String doPost(String url, Map<String, Object> paramMap) throws UnsupportedEncodingException {
        //獲取輸入流
        InputStream is = null;
        BufferedReader br = null;
        String result = null;

        //創建httpClient實例對象
        HttpClient httpClient = new HttpClient();
        //設置httpClient連接主機服務器超時時間:15000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);

        //創建post請求方法實例對象
        PostMethod postMethod = new PostMethod(url);
        //設置post請求超時時間
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);

        NameValuePair[] nvp = null;
        //判斷參數map集合paramMap是否爲空
        if (null != paramMap && paramMap.size() > 0) {//不爲空
            //創建鍵值參數對象數組,大小爲參數的個數
            nvp = new NameValuePair[paramMap.size()];
            //循環遍歷參數集合map
            Set<Entry<String, Object>> entrySet = paramMap.entrySet();
            //獲取迭代器
            Iterator<Entry<String, Object>> iterator = entrySet.iterator();

            int index = 0;
            while (iterator.hasNext()) {
                Entry<String, Object> mapEntry = iterator.next();
                //從mapEntry中獲取key和value創建鍵值對象存放到數組中
                nvp[index] = new NameValuePair(mapEntry.getKey(), new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
                index++;
            }
        }

        //判斷nvp數組是否爲空
        if (null != nvp && nvp.length > 0) {
            //將參數存放到requestBody對象中
            postMethod.setRequestBody(nvp);
        }

        try {
            //執行POST方法
            int statusCode = httpClient.executeMethod(postMethod);
            //判斷是否成功
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method faild: " + postMethod.getStatusLine());
            }

            //獲取遠程返回的數據
            is = postMethod.getResponseBodyAsStream();
            //封裝輸入流
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp).append("\r\n");
            }

            result = sbf.toString();

        } catch (Exception e) {
            System.err.println("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } finally {
            //關閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //釋放連接
            postMethod.releaseConnection();
        }
        return result;
    }
}

4. 使用httpclient4.5版本

相比4.0以前的版本,4.0之後的版本做了一些優化,更簡潔一些

doGet()關鍵步驟:

  • 創建HttpClients對象,通過url創建HttpGet遠程連接對象
  • 創建一個請求參數配置類,設置請求參數
  • 執行請求,獲取數據,轉爲字符串
  • 關閉連接

doPost()關鍵步驟:

  • 創建HttpClients對象,通過url創建HttpPost遠程連接對象
  • 創建一個請求參數配置類,設置請求參數
  • 將參數存入請求體中(使用數組,數組中的元素是鍵值對,鍵是參數名,值是二進制數據)
  • 執行請求,獲取數據,轉爲字符串
  • 關閉連接
package com.bjpowernode.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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;

public class HttpClientTest03 {

    /**
     * Get 請求方法
     *
     * @param url
     * @return
     */
    public static String doGet(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";

        try {
            //通過址默認配置創建一個httpClient實例
            httpClient = HttpClients.createDefault();
            //創建httpGet遠程連接實例
            HttpGet httpGet = new HttpGet(url);
            //設置配置請求參數
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(35000)//連接主機服務超時時間
                    .setConnectionRequestTimeout(35000)//請求超時時間
                    .setSocketTimeout(60000)//數據讀取超時時間
                    .build();
            //爲httpGet實例設置配置
            httpGet.setConfig(requestConfig);
            //執行get請求得到返回對象
            response = httpClient.execute(httpGet);
            //通過返回對象獲取返回數據
            HttpEntity entity = response.getEntity();
            //通過EntityUtils中的toString方法將結果轉換爲字符串
            result = EntityUtils.toString(entity);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //關閉資源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return result;
    }

    public static String doPost(String url, Map<String, Object> paramMap) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";

        try {
            //創建httpClient實例
            httpClient = HttpClients.createDefault();
            //創建httpPost遠程連接實例
            HttpPost httpPost = new HttpPost(url);
            //配置請求參數實例
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(35000)//設置連接主機服務超時時間
                    .setConnectionRequestTimeout(35000)//設置連接請求超時時間
                    .setSocketTimeout(60000)//設置讀取數據連接超時時間
                    .build();
            //爲httpPost實例設置配置
            httpPost.setConfig(requestConfig);

            //封裝post請求參數
            if (null != paramMap && paramMap.size() > 0) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                //通過map集成entrySet方法獲取entity
                Set<Entry<String, Object>> entrySet = paramMap.entrySet();
                //循環遍歷,獲取迭代器
                Iterator<Entry<String, Object>> iterator = entrySet.iterator();
                while (iterator.hasNext()) {
                    Entry<String, Object> mapEntry = iterator.next();
                    nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
                }

                //爲httpPost設置封裝好的請求參數
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            }

            //執行post請求得到返回對象
            response = httpClient.execute(httpPost);
            //通過返回對象獲取數據
            HttpEntity entity = response.getEntity();
            //將返回的數據轉換爲字符串
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //關閉資源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}

五、調用第三方接口

1. 短信驗證碼

短信驗證碼的格式是由國家工信部制定的模版:
短信模版包含兩部分:

  1. 短信簽名:【公司簡稱】
  2. 短信正文:您的短信驗證碼是:563256,請在1分鐘內輸入!

公司按照模版填充內容之後必須由工信部進行審覈,通過之後纔可以使用

騰訊雲-短信平臺

  1. 國內短信由簽名+正文組成,簽名符號爲【】(注:全角),發送短信內容時必須帶簽名;
  2. 短信簽名和模板提交後,預計2小時完成審覈。審覈時間:週一至週日9:00-23:00(法定節假日正常服務);
  3. 您可設置常用手機和郵箱,用於即時接收該應用短信內容審覈通知。 立即設置

2. API接口文檔

各個雲平臺都提供有api接口,這裏拿京東萬象來舉例:https://wx.jdcloud.com/api_1_27

每個服務商所提供的api中參數都不一定相同,就要求要會看api文檔。

(1)接口地址與請求模版

在這裏插入圖片描述

(2)請求/響應參數

請求參數,又叫請求報文

  • appkey:平臺提供,用於辨別用戶
    在這裏插入圖片描述
    響應參數,又叫響應報文
    在這裏插入圖片描述

(3)響應參數示例

在這裏插入圖片描述

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