短信验证码实现

一、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)响应参数示例

在这里插入图片描述

发布了45 篇原创文章 · 获赞 46 · 访问量 1820

猜你喜欢

转载自blog.csdn.net/zyx1260168395/article/details/103747807