迷彩风情的gravatar头像
迷彩风情 2014-06-25 15:43:23

Java调用WebService接口实现发送手机短信验证码功能

近来由于项目需要,需要用到手机短信验证码的功能,其中最主要的是用到了第三方提供的短信平台接口WebService客户端接口,下面我把我在项目中用到的记录一下,以便给大家提供个思路,由于本人的文采有限,还请大家见谅!

一:首先上几张案例截图,以便大家可以了解一下短信验证码的流程,这里我在做的过程中也参考了很多网站的短信验证码,比如:58同城,汽车之家等。

1.点击获取验证码之前的样式:

Java调用WebService接口实现发送手机短信验证码功能

2.输入正确的手机号后点击获取验证码之后的样式:

Java调用WebService接口实现发送手机短信验证码功能

3.如果手机号已经被注册的样式:

Java调用WebService接口实现发送手机短信验证码功能

4.如果一个手机号一天发送超过3次就提示不能发送:

Java调用WebService接口实现发送手机短信验证码功能

二:前台的注册页面的代码:reg.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%@page import="cn.gov.csrc.base.action.FindAllData"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>中国证券会证券期货违法违规举报中心-注册</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="shortcut icon" type="image/x-icon" href="<%=request.getContextPath()%>/images/favicon.ico" />
<link rel="stylesheet" type="text/css"
	href="<%=request.getContextPath()%>/css/main.css">
<link
	href="<%=request.getContextPath()%>/formValidator1/style/validator.css"
	rel="stylesheet" type="text/css" />
<style type="text/css">
button {
	background: #F0F0F0 repeat-x;
	padding-top: 3px; 
	border-top : 1px solid #708090;
	border-right: 1px solid #708090;
	border-bottom: 1px solid #708090;
	border-left: 1px solid #708090;
	width: auto;
	line-height: 12pt; 
	font-size : 10pt;
	cursor: hand;
	font-size: 10pt;
	border-top: 1px solid #708090;
}
</style>
<script src="<%=request.getContextPath()%>/js/jquery-1.7.2.min.js"
	type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/formValidator1/formValidator-4.0.1.js"
	type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/formValidator1/formValidatorRegex.js"
	type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/js/register.js"
	type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/js/sms.js"
	type="text/javascript"></script>
<script type="text/javascript">
	function changeCheckNum() {
		var checkNumImage_ = document.getElementById("checkNumImage");
		checkNumImage_.src = "${pageContext.request.contextPath}/image.jsp?timeStamp="+ new Date().getTime();
	}
</script>
<script type="text/javascript">
	var msg = "${message}";
	if (msg != "") {
		alert(msg);
	}
</script>
</head>
<body>
	<%@include file="/statics/top.jspf"%>
	<div class="center_division">
		<div class="center_body">
			<div class="center_menu">
				<font color="#000000">当前位置:</font>
				<a href="<%=request.getContextPath()%>/statics/reg.jsp"><font color="#000000">用户注册</font></a>
			</div>
		</div>
		<div class="center_body_menu">
			<s:form action="RegisterAction_register" id="form1" name="form1" method="post" namespace="/">
				<table id="tb">
					<tr>
						<td colspan="3" align="center" bgcolor="#DDDFE1">举报人基本信息</td>
					</tr>
					<tr>
						<td align="center" width="30%">&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/new_reg_xing.gif"/>用户名:</td>
						<td align="center" width="40%">
							<s:textfield name="username" id="username" cssStyle="width:160px;height:24px;" onblur="checkusername()"/>
						</td>
						<td align="left" width="30%">
							<span id="usernameTip">
								<s:fielderror cssStyle="color:red;padding-left:10px;">
									<s:param>username</s:param>
								</s:fielderror>
							</span>
						</td>
					</tr>
					<tr>
						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>登录密码:</td>
						<td align="center" width="40%">
							<s:password name="password" id="password" cssStyle="width:160px;height:24px;" onblur="checkpassword()"/>
						</td>
						<td align="left" width="30%">
							<span id="passwordTip">
								<s:fielderror cssStyle="color:red;padding-left:10px;">
									<s:param>password</s:param>
								</s:fielderror>
							</span>
						</td>
					</tr>
					<tr>
						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>确认密码:</td>
						<td align="center" width="40%">
							<s:password name="passwordRepeat" id="passwordRepeat" cssStyle="width:160px;height:24px;" onblur="checkpasswrodb()"/>
						</td>
						<td align="left" width="30%">
							<span id="passwordRepeatTip">
								<s:fielderror cssStyle="color:red;padding-left:10px;">
									<s:param>passwordRepeat</s:param>
								</s:fielderror>
							</span>
						</td>
					</tr>
					<tr>
						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:</td>
						<td align="center" width="40%">
							<s:textfield name="nickname" id="nickname" cssStyle="width:160px;height:24px;" onblur="checknickname()"/>
						</td>
						<td align="left" width="30%">
							<span id="nicknameTip">
								<s:fielderror cssStyle="color:red;padding-left:10px;">
									<s:param>nickname</s:param>
								</s:fielderror>
							</span>
						</td>
					</tr>
					<tr>
						<td align="center" width="30%">性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</td>
						<td align="center" width="40%">
							<s:radio list="#application.dataMap.get('10001')" name="jbSex" cssStyle="height:24px;"/>
						</td>
						<td align="left" width="30%"></td>
					</tr>
					<tr>
						<td align="center" width="30%">联系地址:</td>
						<td align="center" width="40%">
							<s:textfield name="jbAddress" id="jbAddress" cssStyle="width:160px;height:24px;" />
						</td>
						<td align="left" width="30%">
							<span id="jbAddressTip">
								<s:fielderror cssStyle="color:red;padding-left:10px;">
									<s:param>jbAddress</s:param>
								</s:fielderror>
							</span>
						</td>
					</tr>
					<tr>
						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>联系手机:</td>
						<td align="center" width="40%">
							<s:textfield id="jbPhone" name="jbPhone" cssStyle="width:160px;height:24px;" onblur="checkjbPhone()"/>
						</td>
						<td align="left" width="30%">
							<span id="jbPhoneTip">
								<s:fielderror cssStyle="color:red;padding-left:10px;">
									<s:param>jbPhone</s:param>
								</s:fielderror>
							</span>
						</td>
					</tr>
					<tr>
						<td align="center"><img src="images/new_reg_xing.gif"/>短信验证码:</td>
						<td align="left" colspan="2" style="padding-left: 112px;">
							<s:textfield id="SmsCheckCode" name="SmsCheckCode" cssStyle="width:80px;height:24px;" maxLength="6" />
							<span><input type="button" id="btnSendCode" name="btnSendCode" value="免费获取验证码" onclick="sendMessage()" /></span>
							<span id="SmsCheckCodeTip">
								<s:fielderror cssStyle="color:red;padding-left:10px;">
									<s:param>SmsCheckCodeTip</s:param>
								</s:fielderror>
							</span>
						</td>
					</tr>
					<tr>
						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>证件类型:</td>
						<td align="center" width="40%">
						<s:select list="#application.dataMap.get('10002')" label=""
								headerKey="" headerValue="--请选择--" value="1" listValue="value" onchange="enableCredentialsCode(this)"
								name="jbCredentialsName" id="jbCredentialsName" cssStyle="width:160px;height:24px;"/>
						</td>
						<td align="left" width="30%">
							<s:fielderror cssStyle="color:red;padding-left:10px;">
								<s:param>jbCredentialsName</s:param>
							</s:fielderror>
						</td>
					</tr>
					<tr>
						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>证件号码:</td>
						<td align="center" width="40%">
							<s:textfield name="jbCredentialsCode" id="jbCredentialsCode" cssStyle="width:160px;height:24px;" onblur="checkjbCredentialsCode()"/>
						</td>
						<td align="left" width="30%">
							<span id="jbCredentialsCodeTip">
								<s:fielderror cssStyle="color:red;padding-left:10px;">
									<s:param>jbCredentialsCode</s:param>
								</s:fielderror>
							</span>
						</td>
					</tr>
					<tr>
						<td align="center" width="30%">单位名称:</td>
						<td align="center" width="40%">
							<s:textfield name="jbCompanyName" id="jbCompanyName" cssStyle="width:160px;height:24px;" />
						</td>
						<td align="left" width="30%">
							<span id="jbCompanyNameTip">
								<s:fielderror cssStyle="color:red;padding-left:10px;">
									<s:param>jbCompanyName</s:param>
								</s:fielderror>
							</span>
						</td>
					</tr>
					<tr>
						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>所在地区:</td>
						<td align="center" width="40%">
						<s:select list="#application.dataMap.get('10003')" label=""
								headerKey="" headerValue="--请选择--" listKey="key"
								cssStyle="width:160px;height:24px;" listValue="value" id="jbSourceArea"
								name="jbSourceArea" onblur="checkjbSourceArea()"/>
						</td>
						<td align="left" width="30%">
							<span id="jbSourceAreaTip">
								<s:fielderror cssStyle="color:red;padding-left:10px;">
									<s:param>jbSourceArea</s:param>
								</s:fielderror>
							</span>
						</td>
					</tr>
					<tr>
						<td align="center" width="30%">&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/new_reg_xing.gif"/>验证码:</td>
						<td align="center" width="40%">
							<s:textfield id="checkNum" name="checkNum" cssStyle="width:60px;height:24px;" onblur="checkNumber()" maxLength="4"/>
							<img id="checkNumImage" src="${pageContext.request.contextPath}/image.jsp">
							<a onClick="changeCheckNum()" title="点击换一张" style="cursor:hand;">&nbsp;换一张</a>
						</td>
						<td align="left" width="30%">
							<span id="checkNumTip">
								<s:fielderror cssStyle="color:red;padding-left:10px;">
									<s:param>checkNumTip</s:param>
								</s:fielderror>
							</span>
						</td>
					</tr>
					<tr>
						<td colspan="3" style="vertical-align: top; padding-top: 5px;padding-bottom: 5px;">
							<input type="submit" value="注册" style="width:50px; height:24px;"/>
							&nbsp;&nbsp;
							<input type="reset" value="重置" style="width:50px; height:24px;"/>
						</td>
					</tr>
				</table>
			</s:form>
		</div>
	</div>
	<%@include file="/common/buttom.jspf"%>
</body>
</html>

三:前台获取短信验证码的js:sms.js

var InterValObj; //timer变量,控制时间
var count = 120; //间隔函数,1秒执行
var curCount;//当前剩余秒数
var code = ""; //验证码
var codeLength = 6;//验证码长度

function sendMessage() {
	curCount = count;
	var jbPhone = $("#jbPhone").val();
	var jbPhoneTip = $("#jbPhoneTip").text();
	if (jbPhone != "") {
		if(jbPhoneTip == "√ 该手机号码可以注册,输入正确" || jbPhoneTip == "√ 短信验证码已发到您的手机,请查收"){
			// 产生验证码
			for ( var i = 0; i < codeLength; i++) {
				code += parseInt(Math.random() * 9).toString();
			}
			// 设置button效果,开始计时
			$("#btnSendCode").attr("disabled", "true");
			$("#btnSendCode").val("请在" + curCount + "秒内输入验证码");
			InterValObj = window.setInterval(SetRemainTime, 1000); // 启动计时器,1秒执行一次
			// 向后台发送处理数据
			$.ajax({
				type: "POST", // 用POST方式传输
				dataType: "text", // 数据格式:JSON
				url: "UserAction_sms.action", // 目标地址
				data: "jbPhone=" + jbPhone +"&code=" + code,
				error: function (XMLHttpRequest, textStatus, errorThrown) { 
					
				},
				success: function (data){ 
					data = parseInt(data, 10);
					if(data == 1){
						$("#jbPhoneTip").html("<font color='#339933'>√ 短信验证码已发到您的手机,请查收</font>");
					}else if(data == 0){
						$("#jbPhoneTip").html("<font color='red'>× 短信验证码发送失败,请重新发送</font>");
					}else if(data == 2){
						$("#jbPhoneTip").html("<font color='red'>× 该手机号码今天发送验证码过多</font>");
					}
				}
			});
		}
	}else{
		$("#jbPhoneTip").html("<font color='red'>× 手机号码不能为空</font>");
	}
}

//timer处理函数
function SetRemainTime() {
	if (curCount == 0) {                
		window.clearInterval(InterValObj);// 停止计时器
		$("#btnSendCode").removeAttr("disabled");// 启用按钮
		$("#btnSendCode").val("重新发送验证码");
		code = ""; // 清除验证码。如果不清除,过时间后,输入收到的验证码依然有效
	}else {
		curCount--;
		$("#btnSendCode").val("请在" + curCount + "秒内输入验证码");
	}
}

$(document).ready(function() {
	$("#SmsCheckCode").blur(function() {
		var SmsCheckCodeVal = $("#SmsCheckCode").val();
		// 向后台发送处理数据
		$.ajax({
			url : "UserAction_checkCode.action", 
			data : {SmsCheckCode : SmsCheckCodeVal}, 
			type : "POST", 
			dataType : "text", 
			success : function(data) {
				data = parseInt(data, 10);
				if (data == 1) {
					$("#SmsCheckCodeTip").html("<font color='#339933'>√ 短信验证码正确,请继续</font>");
				} else {
					$("#SmsCheckCodeTip").html("<font color='red'>× 短信验证码有误,请核实后重新填写</font>");
				}
			}
		});
	});
});

四:后台action的代码:UserAction.java(这里只是调用了我们的第三方给提供的客户端代码的发送短信的方法,如果是调用其他的短信平台,可以换成他们的发送短信的方法,这里只是给大家做个参考)

/**
	 * 验证手机短信是否发送成功
	 * 
	 * @throws Exception
	 */
	@Action(value = "UserAction_sms")
	public void sms() throws Exception {
		String result = "0";
		/** 手机号码 */
		String jbPhone = WebContextUtil.getRequest().getParameter("jbPhone");
		/** 短信验证码 */
		String code = WebContextUtil.getRequest().getParameter("code");
		/** 短信验证码存入session(session的默认失效时间30分钟) */
		WebContextUtil.getSession().setAttribute("code", code);
		/** 如何初始化失败返回 */
		if(!initClient()) {
			return;
		}
		/** 单个手机号发送短信的方法的参数准备 */
		// 手机号码
		String mobilephone = jbPhone;
		// 短信内容+随机生成的6位短信验证码
		String content = "根据中国证监会举报中心委托,特向您发送此条短信。您的注册验证码为:" + code;
		// 操作用户的ID
		Integer operId = Integer.parseInt(Env.getInstance().getProperty("operId"));
		// 定时发送的的发送时间(缺省为空,如果即时发送,填空)
		String tosend_time = "";
		// 应用系统的短信ID,用户查询该短信的状态报告(缺省为0,即不需查询短信的状态报告)
		int sms_id = 0;
		// 黑名单过滤(0:不需要黑名单过滤,1:需要黑名单过滤,缺省为0)
		short backlist_filter = 0;
		// 禁止语过滤(0:不需要禁止语过滤,1:需要禁止语过滤,缺省为0)
		short fbdword_filter = 0;
		// 优先级(值越大优先级越高,0:普通,1,:优先,2:最高,缺省为0)
		short priority = 0;
		// 短信有效时间(格式为:YYYY-MM-DD HH:mm:ss目前为空)
		String valid_time = "";
		/** 发送短信之前先统计一个已经发送的短信条数 */
		int messageCount = countService.findAllRecord(mobilephone);
		System.out.println("已发短信条数为:" +messageCount);
		if(messageCount < 5){
			/** 单个手机号发送短信 */
			if (!sendMessage(mobilephone, content, operId, tosend_time, sms_id,
					backlist_filter, fbdword_filter, priority, valid_time)) {
				result = "0";// 失败
			} else {
				result = "1";// 成功
				/** 发送一条短信,记录一条短信记录,为了方便之后的统计短信发送次数 */
				count.setPhone(mobilephone);// 手机号码
				count.setCaptcha(code);// 短信验证码
				count.setSendTime(CommonUtil.getNowDate());// 短信发送时间
				if(count != null){
					countService.saveEntity(count);
					System.out.println("保存成功!");
				}
			}
		}else{
			System.out.println("该手机号码今天发送验证码过多");
			result = "2";//一个手机号码最多发送3条短信验证码
		}
		HttpServletResponse response = WebContextUtil.getResponse();
		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.write(result.toString());
	}
	
	/**
	 * WebService客户端初始化
	 * 
	 */
	public static boolean initClient() {
		/**
		 * 判断客户端是否已经初始化
		 */
		if (!SmsWebClient.enable()) {
			int ret = 0;
			try {
				ret = SmsWebClient.init(url, userName, passWord);
				if (ret == -1 || !SmsWebClient.enable()) {
					System.out.println("短信平台接口初始化失败!");
					return false;
				}
				System.out.println("短信平台接口初始化成功!"+ret+"----------");
			} catch (Exception ex) {
				ex.printStackTrace();
				System.out.println("短信平台接口初始化过程中异常!");
			}
		}
		return true;
	}
	
	/**
	 * 单个手机号码发送
	 * 
	 * @param mobilephone
	 *            手机号
	 * @param content
	 *            短信内容
	 * @param operId
	 *            操作用户的ID
	 * @param tosend_time
	 *            定时发送的发送时间
	 * @param sms_id
	 *            应用系统的短信ID
	 * @param backlist_filter
	 *            黑名单过滤
	 * @param fbdword_filter
	 *            禁止语过滤
	 * @param priority
	 *            优先级
	 * @param valid_time
	 *            短信有效时间
	 */
	public static boolean sendMessage(java.lang.String mobilephone,
			java.lang.String content, int operId, java.lang.String tosend_time,
			int sms_id, short backlist_filter, short fbdword_filter,
			short priority, java.lang.String valid_time) {
		// 单个手机号码发送
		try {
			SmsReturnObj retObj = SmsWebClient.webSendMessage(mobilephone,
					content, operId, tosend_time, sms_id, backlist_filter,
					fbdword_filter, priority, valid_time);
			if (retObj.getReturnCode() != 1) {
				System.out.println("短信发送失败,原因为:" + retObj.getReturnMsg());
				return false;
			} else {
				System.out.println("短信发送成功!返回结果为:" + retObj.getReturnMsg());
				return true;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("短信发送过程发生异常!");
		}
		return true;
	}
	

五:具体的短信接口demo到这里下,这里你下载了也不能成功的发送短信,因为你必须要短信平台商给你提供:url,userName,passWord,operId,以及短信平台商还要绑定你的外网ip地址,这样才能真正的发送短信。

链接: http://pan.baidu.com/s/1pJLRsxX

详情请看:http://blog.csdn.net/sxdtzhaoxinguo/article/details/34437591


最代码官方编辑于2016-12-12 10:16:01


打赏

文件名:短信外网接口.zip,文件大小:8626.246K 下载
  • /
      • /短信外网接口
        • /短信外网接口/sms-web-ws-1.0.jar
        • /短信外网接口/smsWebapiDemo.rar
        • /短信外网接口/中国结算短信平台WS接口API调用说明(外网).doc
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友