首页 > 其他 > 详细

短信验证

时间:2021-02-08 10:52:35      阅读:17      评论:0      收藏:0      [点我收藏+]

短信验证

前言

该篇用于:京东万象106短信验证,按步骤拷贝即用,本人也是为了方便自己才写的这个,因为我也不太懂这个,写好后的东西,进行整合上传,方便以后拷贝即用和参考

前端知识
  1. 使用到:轻量级倒计时,请参考使用方法,下方也给出了简单使用案例

  2. 使用到的 js:leftTime.min.js

    <script type="text/javascript"> 
        $(function(){ 
            //60秒倒计时 
            $("#dateBtn1").on("click",function(){ 
                var _this=$(this); 
                if(!$(this).hasClass("on")){ 
                    $.leftTime(60,function(d){ 
                        if(d.status){ 
                            _this.addClass("on"); 
                            _this.html((d.s=="00"?"60":d.s)+"秒后重新获取"); 
                        }else{ 
                            _this.removeClass("on"); 
                            _this.html("获取验证码"); 
                        } 
                    }); 
                } 
            }); 
        }); 
    </script> 
    
  3. HTML:拷贝即用

    <style type="text/css">
    			.testBtn-a{display: inline-block;height:30px;line-height:30px;padding:0 10px; border:0; border-radius:5px;color:#fff;background:rgb(65,133,244);cursor: pointer;}
    			.testBtn-a.on{background:#c9c9c9;color:#666;cursor: default;}
    		</style>
    		
    		
    		<div class="login-yzm">
    			<div id="a" class="yzm-box" style="display:block;">
    			    <input id="messageCode" type="text" class="yzm" placeholder="获取短信验证码"
    				   onblur="checkMessageCode();"/>
    			    <a style=‘cursor:pointer;‘>
    				<button type="button" class="testBtn-a" id="dateBtn1">获取验证码</button>
    			    </a>
    			</div>
    		
    			<ul>
    			    <li id="showId"
    				style="color:red;font-size:12px;width:222px;margin-top:10px;margin-bottom:10px;line-height:18px;"></li>
    			</ul>
    		</div>
    
验证短信的组成
  1. 短信签名:必须由【xxx】,其中xxx 是公司简称
  2. 短信正文:您的短信验证码是:123456,一分钟内有效
短信解析
  1. SAX解析
  2. DOM解析
区别
  1. sax解析是边读边解析
  2. DOM解析是一次性将解析的内容加载到内存,然后再开始解析
  3. 根本区别:DOM解析可以对文档中的节点进行增删改,而sax只能读取信息
使用DOM解析

在这里,我们只演示Dom4j + xpath解析

  1. xPath语法参考

    解析需要使用到xPath语法,请参考以上网址内容

  2. 导入依赖

    <!--DOM解析依赖-->
    <dependency>
        <groupId>org.dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>2.1.0</version>
    </dependency>
    <!--
    	注意高版本dom4j需要导入依赖:jaxen:jaxen,这里我们使用的是2.1.0版本,maven会自动帮我们把相关jaxen:jaxen依赖导入
    	高版本需要注意,可能需要自己手动导入
    <dependency>
        <groupId>jaxen</groupId>
        <artifactId>jaxen</artifactId>
        <version>1.1.6</version>
    </dependency>
    -->
     <!--短信验证-->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
    </dependency>
    
短信验证需要用到的工具类

直接拷贝即用

package com.bjpowernode.httpclient;

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 HttpClientUtils{

	/**
	 * 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;
	}
}
短信报文格式
{
    "code": "10000",
    "charge": false,
    "remain": 0,
    "msg": "查询成功",
    "result": "<?xml version=\"1.0\" encoding=\"utf-8\" ?><returnsms>\n <returnstatus>Success</returnstatus>\n <message>ok</message>\n <remainpoint>-1111611</remainpoint>\n <taskID>101609164</taskID>\n <successCounts>1</successCounts></returnsms>"
}
<!--
	这是result的内容,短信是传递json,在 json中套写xml
-->
<?xml version="1.0" encoding="utf-8" ?>
<returnsms>
	<returnstatus>Success</returnstatus>
	<message>ok</message>
	<remainpoint>-1111611</remainpoint>
	<taskID>101609164</taskID>
	<successCounts>1</successCounts>
</returnsms>
短信验证接口

直接拷贝即用

 /**
     * 短信验证,
     * @param phone
     * @return
     */
    @PostMapping("/user/message/test")
    @ResponseBody
    public Result userMessageTest(@RequestParam(value = "phone",required = true)String phone)
    {

        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("appkey", "14d8136429fba5449d168854e51d88f9");
            //手机号
            paramMap.put("mobile", phone);
            //number:获取随机的短信验证码
            String number = this.getRandomNumber(6);
            //短信的内容,因为是免费短信,所以 内容不可更改
            paramMap.put("content", "【凯信通】您的验证码是:"+number);

            //发送短信,调用京东万象平台的106短信接口(5次免费试用)
            String jsonString = HttpClientUtils.doPost("https://way.jd.com/kaixintong/kaixintong", paramMap);

            //模拟报文,在appkey没有对应的值用时,可以放开下面的代码进行模拟使用
            /*String jsonString = "{\n" +
                    "    \"code\": \"10000\",\n" +
                    "    \"charge\": false,\n" +
                    "    \"remain\": 0,\n" +
                    "    \"msg\": \"查询成功\",\n" +
                    "    \"result\": \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\" ?><returnsms>\\n <returnstatus>Success</returnstatus>\\n <message>ok</message>\\n <remainpoint>-1111611</remainpoint>\\n <taskID>101609164</taskID>\\n <successCounts>1</successCounts></returnsms>\"\n" +
                    "}";*/

            //解析JSONString,试用fastjson来解析
            //第一步,将json格式的字符串解析成JSON对象
            JSONObject jsonObject = JSON.parseObject(jsonString);
            //获取通信表示code
            String code = jsonObject.getString("code");
            //判断是否通信成功,试用的是commons.lang3包的StringUtils
            if(!StringUtils.equals("10000",code)){
                return Result.error("通信异常");
            }
            //获取result对应的xml格式的字符串
            String resultXMLString = jsonObject.getString("result");
            //使用DOM4j+jaxen解析xml格式 字符串
            //将xml 格式的字符串转换成document对象
            Document document = DocumentHelper.parseText(resultXMLString);
            //获取节点文本内容
            Node node = document.selectSingleNode("//returnstatus");
            //获取节点的文本
            String text = node.getText();
            //判断是否发送成功
            if(!StringUtils.equals("Success",text)){
                return Result.error("短信发送失败");
            }
            //短信发送成功,将短信验证码放入到redis中进行缓存
            redisService.put(phone,number);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("短信平台出错");
        }
        return Result.success();
    }

    private String getRandomNumber(int count) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < count; i++) {
            long round = Math.round(Math.random() * 9);
            sb.append(round);
        }
        return sb.toString();
    }
总结

OK,从前端到后端,步骤应该比较全,按步骤来,一步一步copy,不同的短信写的代码也不一样,仅供参考

短信验证

原文:https://www.cnblogs.com/letgofishing/p/14387526.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!