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

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

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

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


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


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


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


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

[html] view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@taglib prefix="s" uri="/struts-tags"%>  
  3. <%@page import="cn.gov.csrc.base.action.FindAllData"%>  
  4. <%  
  5.     String path = request.getContextPath();  
  6.     String basePath = request.getScheme() + "://"  
  7.             + request.getServerName() + ":" + request.getServerPort()  
  8.             + path + "/";  
  9. %>  
  10. >  
  11. <html>  
  12. <head>  
  13. <base href="<%=basePath%>">  
  14. <title>中国证券会证券期货违法违规举报中心-注册title>  
  15. <meta http-equiv="pragma" content="no-cache">  
  16. <meta http-equiv="cache-control" content="no-cache">  
  17. <meta http-equiv="expires" content="0">  
  18. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  19. <meta http-equiv="description" content="This is my page">  
  20. <link rel="shortcut icon" type="image/x-icon" href="<%=request.getContextPath()%>/images/favicon.ico" />  
  21. <link rel="stylesheet" type="text/css"  
  22.     href="<%=request.getContextPath()%>/css/main.css">  
  23. <link  
  24.     href="<%=request.getContextPath()%>/formValidator1/style/validator.css"  
  25.     rel="stylesheet" type="text/css" />  
  26. <style type="text/css">  
  27. button {  
  28.     background: #F0F0F0 repeat-x;  
  29.     padding-top: 3px;   
  30.     border-top : 1px solid #708090;  
  31.     border-right: 1px solid #708090;  
  32.     border-bottom: 1px solid #708090;  
  33.     border-left: 1px solid #708090;  
  34.     width: auto;  
  35.     line-height: 12pt;   
  36.     font-size : 10pt;  
  37.     cursor: hand;  
  38.     font-size: 10pt;  
  39.     border-top: 1px solid #708090;  
  40. }  
  41. style>  
  42. <script src="<%=request.getContextPath()%>/js/jquery-1.7.2.min.js"  
  43.     type="text/javascript">script>  
  44. <script src="<%=request.getContextPath()%>/formValidator1/formValidator-4.0.1.js"  
  45.     type="text/javascript">script>  
  46. <script src="<%=request.getContextPath()%>/formValidator1/formValidatorRegex.js"  
  47.     type="text/javascript">script>  
  48. <script src="<%=request.getContextPath()%>/js/register.js"  
  49.     type="text/javascript">script>  
  50. <script src="<%=request.getContextPath()%>/js/sms.js"  
  51.     type="text/javascript">script>  
  52. <script type="text/javascript">  
  53.     function changeCheckNum() {  
  54.         var checkNumImage_ = document.getElementById("checkNumImage");  
  55.         checkNumImage_.src = "${pageContext.request.contextPath}/image.jsp?timeStamp="+ new Date().getTime();  
  56.     }  
  57. script>  
  58. <script type="text/javascript">  
  59.     var msg = "${message}";  
  60.     if (msg != "") {  
  61.         alert(msg);  
  62.     }  
  63. script>  
  64. head>  
  65. <body>  
  66.     <%@include file="/statics/top.jspf"%>  
  67.     <div class="center_division">  
  68.         <div class="center_body">  
  69.             <div class="center_menu">  
  70.                 <font color="#000000">当前位置:font>  
  71.                 <a href="<%=request.getContextPath()%>/statics/reg.jsp"><font color="#000000">用户注册font>a>  
  72.             div>  
  73.         div>  
  74.         <div class="center_body_menu">  
  75.             <s:form action="RegisterAction_register" id="form1" name="form1" method="post" namespace="/">  
  76.                 <table id="tb">  
  77.                     <tr>  
  78.                         <td colspan="3" align="center" bgcolor="#DDDFE1">举报人基本信息td>  
  79.                     tr>  
  80.                     <tr>  
  81.                         <td align="center" width="30%">    <img src="images/new_reg_xing.gif"/>用户名:td>  
  82.                         <td align="center" width="40%">  
  83.                             <s:textfield name="username" id="username" cssStyle="width:160px;height:24px;" onblur="checkusername()"/>  
  84.                         td>  
  85.                         <td align="left" width="30%">  
  86.                             <span id="usernameTip">  
  87.                                 <s:fielderror cssStyle="color:red;padding-left:10px;">  
  88.                                     <s:param>usernames:param>  
  89.                                 s:fielderror>  
  90.                             span>  
  91.                         td>  
  92.                     tr>  
  93.                     <tr>  
  94.                         <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>登录密码:td>  
  95.                         <td align="center" width="40%">  
  96.                             <s:password name="password" id="password" cssStyle="width:160px;height:24px;" onblur="checkpassword()"/>  
  97.                         td>  
  98.                         <td align="left" width="30%">  
  99.                             <span id="passwordTip">  
  100.                                 <s:fielderror cssStyle="color:red;padding-left:10px;">  
  101.                                     <s:param>passwords:param>  
  102.                                 s:fielderror>  
  103.                             span>  
  104.                         td>  
  105.                     tr>  
  106.                     <tr>  
  107.                         <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>确认密码:td>  
  108.                         <td align="center" width="40%">  
  109.                             <s:password name="passwordRepeat" id="passwordRepeat" cssStyle="width:160px;height:24px;" onblur="checkpasswrodb()"/>  
  110.                         td>  
  111.                         <td align="left" width="30%">  
  112.                             <span id="passwordRepeatTip">  
  113.                                 <s:fielderror cssStyle="color:red;padding-left:10px;">  
  114.                                     <s:param>passwordRepeats:param>  
  115.                                 s:fielderror>  
  116.                             span>  
  117.                         td>  
  118.                     tr>  
  119.                     <tr>  
  120.                         <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>姓        名:td>  
  121.                         <td align="center" width="40%">  
  122.                             <s:textfield name="nickname" id="nickname" cssStyle="width:160px;height:24px;" onblur="checknickname()"/>  
  123.                         td>  
  124.                         <td align="left" width="30%">  
  125.                             <span id="nicknameTip">  
  126.                                 <s:fielderror cssStyle="color:red;padding-left:10px;">  
  127.                                     <s:param>nicknames:param>  
  128.                                 s:fielderror>  
  129.                             span>  
  130.                         td>  
  131.                     tr>  
  132.                     <tr>  
  133.                         <td align="center" width="30%">性        别:td>  
  134.                         <td align="center" width="40%">  
  135.                             <s:radio list="#application.dataMap.get('10001')" name="jbSex" cssStyle="height:24px;"/>  
  136.                         td>  
  137.                         <td align="left" width="30%">td>  
  138.                     tr>  
  139.                     <tr>  
  140.                         <td align="center" width="30%">联系地址:td>  
  141.                         <td align="center" width="40%">  
  142.                             <s:textfield name="jbAddress" id="jbAddress" cssStyle="width:160px;height:24px;" />  
  143.                         td>  
  144.                         <td align="left" width="30%">  
  145.                             <span id="jbAddressTip">  
  146.                                 <s:fielderror cssStyle="color:red;padding-left:10px;">  
  147.                                     <s:param>jbAddresss:param>  
  148.                                 s:fielderror>  
  149.                             span>  
  150.                         td>  
  151.                     tr>  
  152.                     <tr>  
  153.                         <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>联系手机:td>  
  154.                         <td align="center" width="40%">  
  155.                             <s:textfield id="jbPhone" name="jbPhone" cssStyle="width:160px;height:24px;" onblur="checkjbPhone()"/>  
  156.                         td>  
  157.                         <td align="left" width="30%">  
  158.                             <span id="jbPhoneTip">  
  159.                                 <s:fielderror cssStyle="color:red;padding-left:10px;">  
  160.                                     <s:param>jbPhones:param>  
  161.                                 s:fielderror>  
  162.                             span>  
  163.                         td>  
  164.                     tr>  
  165.                     <tr>  
  166.                         <td align="center"><img src="images/new_reg_xing.gif"/>短信验证码:td>  
  167.                         <td align="left" colspan="2" style="padding-left: 112px;">  
  168.                             <s:textfield id="SmsCheckCode" name="SmsCheckCode" cssStyle="width:80px;height:24px;" maxLength="6" />  
  169.                             <span><input type="button" id="btnSendCode" name="btnSendCode" value="免费获取验证码" onclick="sendMessage()" />span>  
  170.                             <span id="SmsCheckCodeTip">  
  171.                                 <s:fielderror cssStyle="color:red;padding-left:10px;">  
  172.                                     <s:param>SmsCheckCodeTips:param>  
  173.                                 s:fielderror>  
  174.                             span>  
  175.                         td>  
  176.                     tr>  
  177.                     <tr>  
  178.                         <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>证件类型:td>  
  179.                         <td align="center" width="40%">  
  180.                         <s:select list="#application.dataMap.get('10002')" label=""  
  181.                                 headerKey="" headerValue="--请选择--" value="1" listValue="value" onchange="enableCredentialsCode(this)"  
  182.                                 name="jbCredentialsName" id="jbCredentialsName" cssStyle="width:160px;height:24px;"/>  
  183.                         td>  
  184.                         <td align="left" width="30%">  
  185.                             <s:fielderror cssStyle="color:red;padding-left:10px;">  
  186.                                 <s:param>jbCredentialsNames:param>  
  187.                             s:fielderror>  
  188.                         td>  
  189.                     tr>  
  190.                     <tr>  
  191.                         <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>证件号码:td>  
  192.                         <td align="center" width="40%">  
  193.                             <s:textfield name="jbCredentialsCode" id="jbCredentialsCode" cssStyle="width:160px;height:24px;" onblur="checkjbCredentialsCode()"/>  
  194.                         td>  
  195.                         <td align="left" width="30%">  
  196.                             <span id="jbCredentialsCodeTip">  
  197.                                 <s:fielderror cssStyle="color:red;padding-left:10px;">  
  198.                                     <s:param>jbCredentialsCodes:param>  
  199.                                 s:fielderror>  
  200.                             span>  
  201.                         td>  
  202.                     tr>  
  203.                     <tr>  
  204.                         <td align="center" width="30%">单位名称:td>  
  205.                         <td align="center" width="40%">  
  206.                             <s:textfield name="jbCompanyName" id="jbCompanyName" cssStyle="width:160px;height:24px;" />  
  207.                         td>  
  208.                         <td align="left" width="30%">  
  209.                             <span id="jbCompanyNameTip">  
  210.                                 <s:fielderror cssStyle="color:red;padding-left:10px;">  
  211.                                     <s:param>jbCompanyNames:param>  
  212.                                 s:fielderror>  
  213.                             span>  
  214.                         td>  
  215.                     tr>  
  216.                     <tr>  
  217.                         <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>所在地区:td>  
  218.                         <td align="center" width="40%">  
  219.                         <s:select list="#application.dataMap.get('10003')" label=""  
  220.                                 headerKey="" headerValue="--请选择--" listKey="key"  
  221.                                 cssStyle="width:160px;height:24px;" listValue="value" id="jbSourceArea"  
  222.                                 name="jbSourceArea" onblur="checkjbSourceArea()"/>  
  223.                         td>  
  224.                         <td align="left" width="30%">  
  225.                             <span id="jbSourceAreaTip">  
  226.                                 <s:fielderror cssStyle="color:red;padding-left:10px;">  
  227.                                     <s:param>jbSourceAreas:param>  
  228.                                 s:fielderror>  
  229.                             span>  
  230.                         td>  
  231.                     tr>  
  232.                     <tr>  
  233.                         <td align="center" width="30%">    <img src="images/new_reg_xing.gif"/>验证码:td>  
  234.                         <td align="center" width="40%">  
  235.                             <s:textfield id="checkNum" name="checkNum" cssStyle="width:60px;height:24px;" onblur="checkNumber()" maxLength="4"/>  
  236.                             <img id="checkNumImage" src="${pageContext.request.contextPath}/image.jsp">  
  237.                             <a onClick="changeCheckNum()" title="点击换一张" style="cursor:hand;"> 换一张a>  
  238.                         td>  
  239.                         <td align="left" width="30%">  
  240.                             <span id="checkNumTip">  
  241.                                 <s:fielderror cssStyle="color:red;padding-left:10px;">  
  242.                                     <s:param>checkNumTips:param>  
  243.                                 s:fielderror>  
  244.                             span>  
  245.                         td>  
  246.                     tr>  
  247.                     <tr>  
  248.                         <td colspan="3" style="vertical-align: top; padding-top: 5px;padding-bottom: 5px;">  
  249.                             <input type="submit" value="注册" style="width:50px; height:24px;"/>  
  250.                                 
  251.                             <input type="reset" value="重置" style="width:50px; height:24px;"/>  
  252.                         td>  
  253.                     tr>  
  254.                 table>  
  255.             s:form>  
  256.         div>  
  257.     div>  
  258.     <%@include file="/common/buttom.jspf"%>  
  259. body>  
  260. html>  

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

[javascript] view plain copy
  1. var InterValObj; //timer变量,控制时间  
  2. var count = 120; //间隔函数,1秒执行  
  3. var curCount;//当前剩余秒数  
  4. var code = ""//验证码  
  5. var codeLength = 6;//验证码长度  
  6.   
  7. function sendMessage() {  
  8.     curCount = count;  
  9.     var jbPhone = $("#jbPhone").val();  
  10.     var jbPhoneTip = $("#jbPhoneTip").text();  
  11.     if (jbPhone != "") {  
  12.         if(jbPhoneTip == "√ 该手机号码可以注册,输入正确" || jbPhoneTip == "√ 短信验证码已发到您的手机,请查收"){  
  13.             // 产生验证码  
  14.             for ( var i = 0; i < codeLength; i++) {  
  15.                 code += parseInt(Math.random() * 9).toString();  
  16.             }  
  17.             // 设置button效果,开始计时  
  18.             $("#btnSendCode").attr("disabled""true");  
  19.             $("#btnSendCode").val("请在" + curCount + "秒内输入验证码");  
  20.             InterValObj = window.setInterval(SetRemainTime, 1000); // 启动计时器,1秒执行一次  
  21.             // 向后台发送处理数据  
  22.             $.ajax({  
  23.                 type: "POST"// 用POST方式传输  
  24.                 dataType: "text"// 数据格式:JSON  
  25.                 url: "UserAction_sms.action"// 目标地址  
  26.                 data: "jbPhone=" + jbPhone +"&code=" + code,  
  27.                 error: function (XMLHttpRequest, textStatus, errorThrown) {   
  28.                       
  29.                 },  
  30.                 success: function (data){   
  31.                     data = parseInt(data, 10);  
  32.                     if(data == 1){  
  33.                         $("#jbPhoneTip").html("√ 短信验证码已发到您的手机,请查收");  
  34.                     }else if(data == 0){  
  35.                         $("#jbPhoneTip").html("× 短信验证码发送失败,请重新发送");  
  36.                     }else if(data == 2){  
  37.                         $("#jbPhoneTip").html("× 该手机号码今天发送验证码过多");  
  38.                     }  
  39.                 }  
  40.             });  
  41.         }  
  42.     }else{  
  43.         $("#jbPhoneTip").html("× 手机号码不能为空");  
  44.     }  
  45. }  
  46.   
  47. //timer处理函数  
  48. function SetRemainTime() {  
  49.     if (curCount == 0) {                  
  50.         window.clearInterval(InterValObj);// 停止计时器  
  51.         $("#btnSendCode").removeAttr("disabled");// 启用按钮  
  52.         $("#btnSendCode").val("重新发送验证码");  
  53.         code = ""// 清除验证码。如果不清除,过时间后,输入收到的验证码依然有效  
  54.     }else {  
  55.         curCount--;  
  56.         $("#btnSendCode").val("请在" + curCount + "秒内输入验证码");  
  57.     }  
  58. }  
  59.   
  60. $(document).ready(function() {  
  61.     $("#SmsCheckCode").blur(function() {  
  62.         var SmsCheckCodeVal = $("#SmsCheckCode").val();  
  63.         // 向后台发送处理数据  
  64.         $.ajax({  
  65.             url : "UserAction_checkCode.action",   
  66.             data : {SmsCheckCode : SmsCheckCodeVal},   
  67.             type : "POST",   
  68.             dataType : "text",   
  69.             success : function(data) {  
  70.                 data = parseInt(data, 10);  
  71.                 if (data == 1) {  
  72.                     $("#SmsCheckCodeTip").html("√ 短信验证码正确,请继续");  
  73.                 } else {  
  74.                     $("#SmsCheckCodeTip").html("× 短信验证码有误,请核实后重新填写");  
  75.                 }  
  76.             }  
  77.         });  
  78.     });  
  79. });  


四:验证码用户名和手机号码的js:register.js

[javascript] view plain copy
  1. //去掉前后空格  
  2. function trim(str) {  
  3.     var strnew = str.replace(/^\s*|\s*$/g, "");  
  4.     return strnew;  
  5. }  
  6. //用户名  
  7. function checkusername() {  
  8.     var username = document.form1.username.value;  
  9.     if (username == "" || !isNaN(username.charAt(0))) {  
  10.         document.getElementById("usernameTip").innerHTML = "× 首字母不能为数字或者用户名不能为空";  
  11.         return false;  
  12.     } else if (username.length < 6 || username.length > 30) {  
  13.         document.getElementById("usernameTip").innerHTML = "× 用户名长度为6-30位字符";  
  14.         return false;  
  15.     } else {  
  16.         document.getElementById("usernameTip").innerHTML = "√ 用户名合格";  
  17.         // 向后台发送处理数据  
  18.         $.ajax({  
  19.             url : "UserAction_checkUserName.action",// 目标地址  
  20.             data : {username : username}, // 目标参数  
  21.             type : "POST"// 用POST方式传输  
  22.             dataType : "text"// 数据格式:text  
  23.             success : function(data) {  
  24.                 data = parseInt(data, 10);  
  25.                 if (data != 0) {  
  26.                     $("#usernameTip").html("× 该用户名已经被注册,请重新输入");  
  27.                 } else {  
  28.                     $("#usernameTip").html("√ 该用户名可以注册,输入正确");  
  29.                 }  
  30.             }  
  31.         });  
  32.         return true;  
  33.     }  
  34. }  
  35. // 登录密码  
  36. function checkpassword() {  
  37.     var password = document.form1.password.value;  
  38.     if (password.length < 6 || password.length > 30) {  
  39.         document.getElementById("passwordTip").innerHTML = "× 密码长度不能小于6位,大于30位";  
  40.         return false;  
  41.     } else if (!isNaN(password)) {  
  42.         document.getElementById("passwordTip").innerHTML = "× 密码不能全是数字";  
  43.         return false;  
  44.     } else {  
  45.         document.getElementById("passwordTip").innerHTML = "√ 密码合格";  
  46.         return true;  
  47.     }  
  48. }  
  49. // 确认密码  
  50. function checkpasswrodb() {  
  51.     var password = document.form1.password.value;  
  52.     var passwordRepeat = document.form1.passwordRepeat.value;  
  53.     if (trim(password) != trim(passwordRepeat)) {  
  54.         document.getElementById("passwordRepeatTip").innerHTML = "× 两次密码输入必须一致";  
  55.         return false;  
  56.     } else {  
  57.         document.getElementById("passwordRepeatTip").innerHTML = "√ 密码输入一致";  
  58.         return true;  
  59.     }  
  60. }  
  61. // 姓名  
  62. function checknickname() {  
  63.     var nickname = document.form1.nickname.value;  
  64.     if (trim(nickname) == "") {  
  65.         document.getElementById("nicknameTip").innerHTML = "× 姓名不能为空";  
  66.         return false;  
  67.     } else {  
  68.         document.getElementById("nicknameTip").innerHTML = "√ 姓名输入正确";  
  69.         return true;  
  70.     }  
  71. }  
  72. // 联系手机(ajax验证手机号码是否已经存在)  
  73. function checkjbPhone() {  
  74.     var jbPhone = document.form1.jbPhone.value;  
  75.     var re= /(^1[3|5|8][0-9]{9}$)/;  
  76.     if (trim(jbPhone) == "") {  
  77.         document.getElementById("jbPhoneTip").innerHTML = "× 手机号码不能为空";  
  78.         return false;  
  79.     } else if(trim(jbPhone) != ""){  
  80.         if(!re.test(jbPhone)){  
  81.             document.getElementById("jbPhoneTip").innerHTML = "× 请输入有效的手机号码";  
  82.             return false;  
  83.         }else{  
  84.             document.getElementById("jbPhoneTip").innerHTML = "√ 手机号码输入正确";  
  85.             // 向后台发送处理数据  
  86.             $.ajax({  
  87.                 url : "UserAction_checkPhone.action",// 目标地址  
  88.                 data : {jbPhone : jbPhone}, // 目标参数  
  89.                 type : "POST"// 用POST方式传输  
  90.                 dataType : "text"// 数据格式:text  
  91.                 success : function(data) {  
  92.                     data = parseInt(data, 10);  
  93.                     if (data != 0) {  
  94.                         $("#jbPhoneTip").html("× 该手机号码已经被注册,请重新输入");  
  95.                     } else {  
  96.                         $("#jbPhoneTip").html("√ 该手机号码可以注册,输入正确");  
  97.                     }  
  98.                 }  
  99.             });  
  100.             return true;  
  101.         }  
  102.     }  
  103.       
  104. }  
  105. // 证件号码  
  106. function checkjbCredentialsCode() {  
  107.     var jbCredentialsCode = document.form1.jbCredentialsCode.value;  
  108.     var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;   
  109.     if (trim(jbCredentialsCode) == "") {  
  110.         document.getElementById("jbCredentialsCodeTip").innerHTML = "× 证件号码不能为空";  
  111.         return false;  
  112.     } else if(trim(jbCredentialsCode) != ""){  
  113.         if(!reg.test(jbCredentialsCode)){  
  114.             document.getElementById("jbCredentialsCodeTip").innerHTML = "× 请输入合法的证件号码";  
  115.             return false;  
  116.         }else{  
  117.             document.getElementById("jbCredentialsCodeTip").innerHTML = "√ 证件号码输入正确";  
  118.             // 向后台发送处理数据  
  119.             $.ajax({  
  120.                 url : "UserAction_checkCredentialsCode.action",// 目标地址  
  121.                 data : {jbCredentialsCode : jbCredentialsCode}, // 目标参数  
  122.                 type : "POST"// 用POST方式传输  
  123.                 dataType : "text"// 数据格式:text  
  124.                 success : function(data) {  
  125.                     data = parseInt(data, 10);  
  126.                     if (data != 0) {  
  127.                         $("#jbCredentialsCodeTip").html("× 该证件号码已经被注册,请重新输入");  
  128.                     } else {  
  129.                         $("#jbCredentialsCodeTip").html("√ 该证件号码可以注册,输入正确");  
  130.                     }  
  131.                 }  
  132.             });  
  133.             return true;  
  134.         }  
  135.     }  
  136. }  
  137. // 所在地区  
  138. function checkjbSourceArea() {  
  139.     var jbSourceArea = document.form1.jbSourceArea.value;  
  140.     if (trim(jbSourceArea) == "") {  
  141.         document.getElementById("jbSourceAreaTip").innerHTML = "× 请选择所在地区";  
  142.         return false;  
  143.     } else {  
  144.         document.getElementById("jbSourceAreaTip").innerHTML = "√ 所在地区选择正确";  
  145.         return true;  
  146.     }  
  147. }  
  148. // 验证码  
  149. function checkNumber() {  
  150.     var checkNum = document.form1.checkNum.value;  
  151.     if (trim(checkNum) == "") {  
  152.         document.getElementById("checkNumTip").innerHTML = "× 验证码不能为空";  
  153.         return false;  
  154.     } else {  
  155.         document.getElementById("checkNumTip").innerHTML = "√ 验证码合格";  
  156.         // 向后台发送处理数据  
  157.         $.ajax({  
  158.             url : "UserAction_checkNum.action",// 目标地址  
  159.             data : {checkNum : checkNum}, // 目标参数  
  160.             type : "POST"// 用POST方式传输  
  161.             dataType : "text"// 数据格式:text  
  162.             success : function(data) {  
  163.                 data = parseInt(data, 10);  
  164.                 if (data != 0) {  
  165.                     $("#checkNumTip").html("× 验证码错误");  
  166.                 } else {  
  167.                     $("#checkNumTip").html("√ 验证码正确");  
  168.                 }  
  169.             }  
  170.         });  
  171.         return true;  
  172.     }  
  173. }  


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

[java] view plain copy
  1. package cn.gov.csrc.base.systemmanager.action;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.util.List;  
  6.   
  7. import javax.annotation.Resource;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. import org.apache.log4j.Logger;  
  11. import org.apache.struts2.convention.annotation.Action;  
  12. import org.apache.struts2.convention.annotation.Result;  
  13. import org.apache.struts2.convention.annotation.Results;  
  14. import org.springframework.context.annotation.Scope;  
  15. import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;  
  16. import org.springframework.security.core.context.SecurityContextHolder;  
  17. import org.springframework.stereotype.Controller;  
  18.   
  19. import cn.gov.csrc.base.action.BaseAction;  
  20. import cn.gov.csrc.base.log.service.LogService;  
  21. import cn.gov.csrc.base.report.util.CommonUtil;  
  22. import cn.gov.csrc.base.report.util.Env;  
  23. import cn.gov.csrc.base.systemmanager.model.Count;  
  24. import cn.gov.csrc.base.systemmanager.model.User;  
  25. import cn.gov.csrc.base.systemmanager.service.CountService;  
  26. import cn.gov.csrc.base.systemmanager.service.UserService;  
  27. import cn.gov.csrc.base.util.WebContextUtil;  
  28.   
  29. import com.sms.webservice.client.SmsReturnObj;  
  30. import com.sms.webservice.client.SmsWebClient;  
  31. /** 
  32.  * File: UserAction.java  
  33.  * Author: jiangsai  
  34.  * Version: 1.1  
  35.  * Date: 04/17/2013  
  36.  * Modify: 
  37.  * Description:用户  
  38.  * Copyright csrc 
  39.  */  
  40. @Controller()  
  41. @Scope("prototype")  
  42. @Results({  
  43.         @Result(name = "success", location = "/statics/report.jsp"),  
  44.         @Result(name = "modifyPassword", location = "/statics/modifyPassword.jsp")  
  45.         })  
  46. public class UserAction extends BaseAction {  
  47.       
  48.     private static final long serialVersionUID = 1214696686677691191L;  
  49.     private static Logger log = Logger.getLogger(UserAction.class);  
  50.     private static final String url = Env.getInstance().getProperty("url");  
  51.     private static final String userName = Env.getInstance().getProperty(  
  52.             "username");  
  53.     private static final String passWord = Env.getInstance().getProperty(  
  54.             "password");  
  55.   
  56.     private Integer id;  
  57.   
  58.     private String username;// 用户名  
  59.   
  60.     private String password;// 密码  
  61.   
  62.     private String passwordRepeat;// 确认密码  
  63.       
  64.     private String jbPhone;//手机号码  
  65.       
  66.     private String jbCredentialsCode;//身份证号码  
  67.       
  68.     private String checkNum;//图片验证码  
  69.   
  70.     private String newPassword;  
  71.   
  72.     private String confirmPassword;  
  73.   
  74.     private Integer[] ownRoleIds;  
  75.   
  76.     private UserService userService;  
  77.       
  78.     private CountService countService;  
  79.       
  80.     private LogService logService;  
  81.       
  82.     private Count count = new Count();  
  83.   
  84.     public Integer getId() {  
  85.         return id;  
  86.     }  
  87.   
  88.     public void setId(Integer id) {  
  89.         this.id = id;  
  90.     }  
  91.   
  92.     public String getUsername() {  
  93.         return username;  
  94.     }  
  95.   
  96.     public void setUsername(String username) {  
  97.         this.username = username;  
  98.     }  
  99.   
  100.     public String getPassword() {  
  101.         return password;  
  102.     }  
  103.   
  104.     public void setPassword(String password) {  
  105.         this.password = password;  
  106.     }  
  107.   
  108.     public String getPasswordRepeat() {  
  109.         return passwordRepeat;  
  110.     }  
  111.   
  112.     public void setPasswordRepeat(String passwordRepeat) {  
  113.         this.passwordRepeat = passwordRepeat;  
  114.     }  
  115.       
  116.     public String getJbPhone() {  
  117.         return jbPhone;  
  118.     }  
  119.   
  120.     public void setJbPhone(String jbPhone) {  
  121.         this.jbPhone = jbPhone;  
  122.     }  
  123.       
  124.     public String getJbCredentialsCode() {  
  125.         return jbCredentialsCode;  
  126.     }  
  127.   
  128.     public void setJbCredentialsCode(String jbCredentialsCode) {  
  129.         this.jbCredentialsCode = jbCredentialsCode;  
  130.     }  
  131.   
  132.     public String getCheckNum() {  
  133.         return checkNum;  
  134.     }  
  135.   
  136.     public void setCheckNum(String checkNum) {  
  137.         this.checkNum = checkNum;  
  138.     }  
  139.   
  140.     public Integer[] getOwnRoleIds() {  
  141.         return ownRoleIds;  
  142.     }  
  143.   
  144.     public void setOwnRoleIds(Integer[] ownRoleIds) {  
  145.         this.ownRoleIds = ownRoleIds;  
  146.     }  
  147.   
  148.     public String getNewPassword() {  
  149.         return newPassword;  
  150.     }  
  151.   
  152.     public void setNewPassword(String newPassword) {  
  153.         this.newPassword = newPassword;  
  154.     }  
  155.   
  156.     public String getConfirmPassword() {  
  157.         return confirmPassword;  
  158.     }  
  159.   
  160.     public void setConfirmPassword(String confirmPassword) {  
  161.         this.confirmPassword = confirmPassword;  
  162.     }  
  163.   
  164.     @Resource  
  165.     public void setUserService(UserService userService) {  
  166.         this.userService = userService;  
  167.     }  
  168.   
  169.     public UserService getUserService() {  
  170.         return userService;  
  171.     }  
  172.   
  173.     @Resource  
  174.     public void setCountService(CountService countService) {  
  175.         this.countService = countService;  
  176.     }  
  177.   
  178.     public CountService getCountService() {  
  179.         return countService;  
  180.     }  
  181.       
  182.     public LogService getLogService() {  
  183.         return logService;  
  184.     }  
  185.   
  186.     @Resource  
  187.     public void setLogService(LogService logService) {  
  188.         this.logService = logService;  
  189.     }  
  190.   
  191.     public Count getCount() {  
  192.         return count;  
  193.     }  
  194.   
  195.     public void setCount(Count count) {  
  196.         this.count = count;  
  197.     }  
  198.   
  199.     public void prepareToUpdatePage() {  
  200.         model = userService.getEntity(id);  
  201.     }  
  202.       
  203.     /** 
  204.      * 用户登录 
  205.      *  
  206.      * @return success 
  207.      */  
  208.     @Action(value = "UserAction_login")  
  209.     public String login() {  
  210.         Object u = SecurityContextHolder.getContext().getAuthentication().getPrincipal();  
  211.         if (u instanceof User && u != null) {  
  212.             WebContextUtil.getSession().setAttribute("user", u);  
  213.             User user = (User)u;  
  214.             //使用数据库表TBL_BASE_LOG添加用户登录的日志信息  
  215.             logService.saveTblBaseLog(WebContextUtil.getRequest(),"当前操作人【"+user.getNickname()+"】登录系统");  
  216.         } else {  
  217.             // 防止绕过登陆页面直接执行Action  
  218.             return "login";  
  219.         }  
  220.         return SUCCESS;  
  221.     }  
  222.       
  223.     /** 
  224.      * 用户密码更新 
  225.      */  
  226.     @Action(value = "UserAction_updateUser")  
  227.     public String updateUser() {  
  228.         if (!newPassword.equals(confirmPassword)) {  
  229.             this.setMessage("新密码与确认密码不一致!");  
  230.             return "modifyPassword";  
  231.         }  
  232.         User u = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();  
  233.         MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("md5");  
  234.         String psw = encoder.encodePassword(newPassword, null);  
  235.         userService.modifyPassword(u, psw);  
  236.         this.setMessage("保存成功!");  
  237.         return "modifyPassword";  
  238.     }  
  239.       
  240.     /** 
  241.      * 验证用户名是否存在 
  242.      *  
  243.      * @throws Exception 
  244.      */  
  245.     @Action(value = "UserAction_checkUserName")  
  246.     public void checkUserName(){  
  247.         String result = "0";  
  248.         try {  
  249.             List list = userService.findUserByUserName(username);  
  250.             if(list != null && list.size() > 0){  
  251.                 result = "1";  
  252.             }else{  
  253.                 result = "0";  
  254.             }  
  255.             HttpServletResponse response = WebContextUtil.getResponse();  
  256.             response.setContentType("application/json;charset=UTF-8");  
  257.             response.setHeader("Cache-Control""no-cache");  
  258.             PrintWriter out = response.getWriter();  
  259.             out.write(result.toString());  
  260.         } catch (IOException e) {  
  261.             throw new RuntimeException("验证身份证号码出错", e);  
  262.         }  
  263.     }  
  264.   
  265.     /** 
  266.      * 验证原始密码是否正确 
  267.      *  
  268.      * @throws Exception 
  269.      */  
  270.     @Action(value = "UserAction_checkPassWord")  
  271.     public void checkPassWord() throws Exception {  
  272.         String result = "0";  
  273.         MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("md5");  
  274.         String pwd = encoder.encodePassword(password, null);  
  275.         List user = userService.findUserByPassWord(pwd);  
  276.         if (user != null && user.size() > 0) {  
  277.             result = "1";  
  278.         }else{  
  279.             result = "0";  
  280.         }  
  281.         HttpServletResponse response = WebContextUtil.getResponse();  
  282.         response.setContentType("application/json;charset=UTF-8");  
  283.         response.setHeader("Cache-Control""no-cache");  
  284.         PrintWriter out = response.getWriter();  
  285.         out.write(result.toString());  
  286.     }  
  287.       
  288.     /** 
  289.      * 验证手机号码是否存在 
  290.      */  
  291.     @Action(value = "UserAction_checkPhone")  
  292.     public void checkPhone(){  
  293.         String result = "0";  
  294.         try {  
  295.             List list = userService.findUserByPhone(jbPhone);  
  296.             if(list != null && list.size() > 0){  
  297.                 result = "1";  
  298.             }else{  
  299.                 result = "0";  
  300.             }  
  301.             HttpServletResponse response = WebContextUtil.getResponse();  
  302.             response.setContentType("application/json;charset=UTF-8");  
  303.             response.setHeader("Cache-Control""no-cache");  
  304.             PrintWriter out = response.getWriter();  
  305.             out.write(result.toString());  
  306.         } catch (IOException e) {  
  307.             throw new RuntimeException("验证手机号码出错", e);  
  308.         }  
  309.     }  
  310.       
  311.     /** 
  312.      * 验证身份证号码是否存在 
  313.      */  
  314.     @Action(value = "UserAction_checkCredentialsCode")  
  315.     public void checkCredentialsCode(){  
  316.         String result = "0";  
  317.         try {  
  318.             List list = userService.findUserByCredentialsCode(jbCredentialsCode);  
  319.             if(list != null && list.size() > 0){  
  320.                 result = "1";  
  321.             }else{  
  322.                 result = "0";  
  323.             }  
  324.             HttpServletResponse response = WebContextUtil.getResponse();  
  325.             response.setContentType("application/json;charset=UTF-8");  
  326.             response.setHeader("Cache-Control""no-cache");  
  327.             PrintWriter out = response.getWriter();  
  328.             out.write(result.toString());  
  329.         } catch (IOException e) {  
  330.             throw new RuntimeException("验证身份证号码出错", e);  
  331.         }  
  332.     }  
  333.       
  334.     /** 
  335.      * 验证验证码是否正确 
  336.      */  
  337.     @Action(value = "UserAction_checkNum")  
  338.     public void checkNum(){  
  339.         try {  
  340.             String result = "0";  
  341.             String check_number_key = (String)WebContextUtil.getSession().getAttribute("CHECK_NUMBER_KEY");  
  342.             if(checkNum != check_number_key && !checkNum.equals(check_number_key)){  
  343.                 result = "1";  
  344.             }else{  
  345.                 result = "0";  
  346.             }  
  347.             HttpServletResponse response = WebContextUtil.getResponse();  
  348.             response.setContentType("application/json;charset=UTF-8");  
  349.             response.setHeader("Cache-Control""no-cache");  
  350.             PrintWriter out = response.getWriter();  
  351.             out.write(result.toString());  
  352.         } catch (IOException e) {  
  353.             throw new RuntimeException("验证验证码出错", e);  
  354.         }  
  355.     }  
  356.       
  357.     /** 
  358.      * 验证短信验证码是否正确 
  359.      *  
  360.      * @throws Exception 
  361.      */  
  362.     @Action(value = "UserAction_checkCode")  
  363.     public void checkCode() throws Exception{  
  364.         String result = "0";  
  365.         /** 获取手动输入的手机短信验证码 */  
  366.         String SmsCheckCode = WebContextUtil.getRequest().getParameter("SmsCheckCode");  
  367.         /** 获取session中存放的手机短信验证码 */  
  368.         String code = (String) WebContextUtil.getSession().getAttribute("code");  
  369.         try {  
  370.             if(SmsCheckCode != code && !SmsCheckCode.equals(code)){  
  371.                 result = "0";  
  372.             }else{  
  373.                 result = "1";  
  374.             }  
  375.         } catch (Exception e) {  
  376.             throw new RuntimeException("短信验证失败", e);  
  377.         }  
  378.         HttpServletResponse response = WebContextUtil.getResponse();  
  379.         response.setContentType("application/json;charset=UTF-8");  
  380.         response.setHeader("Cache-Control""no-cache");  
  381.         PrintWriter out = response.getWriter();  
  382.         out.write(result.toString());  
  383.     }  
  384.       
  385.     /** 
  386.      * 验证手机短信是否发送成功 
  387.      *  
  388.      * @throws Exception 
  389.      */  
  390.     @Action(value = "UserAction_sms")  
  391.     public void sms() throws Exception {  
  392.         String result = "0";  
  393.         /** 手机号码 */  
  394.         String jbPhone = WebContextUtil.getRequest().getParameter("jbPhone");  
  395.         /** 短信验证码 */  
  396.         String code = WebContextUtil.getRequest().getParameter("code");  
  397.         /** 短信验证码存入session(session的默认失效时间30分钟) */  
  398.         WebContextUtil.getSession().setAttribute("code", code);  
  399.         /** 如何初始化失败返回 */  
  400.         if(!initClient()) {  
  401.             return;  
  402.         }  
  403.         /** 单个手机号发送短信的方法的参数准备 */  
  404.         // 手机号码  
  405.         String mobilephone = jbPhone;  
  406.         // 短信内容+随机生成的6位短信验证码  
  407.         String content = "根据中国证监会举报中心委托,特向您发送此条短信。您的注册验证码为:" + code;  
  408.         // 操作用户的ID  
  409.         Integer operId = Integer.parseInt(Env.getInstance().getProperty("operId"));  
  410.         // 定时发送的的发送时间(缺省为空,如果即时发送,填空)  
  411.         String tosend_time = "";  
  412.         // 应用系统的短信ID,用户查询该短信的状态报告(缺省为0,即不需查询短信的状态报告)  
  413.         int sms_id = 0;  
  414.         // 黑名单过滤(0:不需要黑名单过滤,1:需要黑名单过滤,缺省为0)  
  415.         short backlist_filter = 0;  
  416.         // 禁止语过滤(0:不需要禁止语过滤,1:需要禁止语过滤,缺省为0)  
  417.         short fbdword_filter = 0;  
  418.         // 优先级(值越大优先级越高,0:普通,1,:优先,2:最高,缺省为0)  
  419.         short priority = 0;  
  420.         // 短信有效时间(格式为:YYYY-MM-DD HH:mm:ss目前为空)  
  421.         String valid_time = "";  
  422.         /** 发送短信之前先统计一个已经发送的短信条数 */  
  423.         int messageCount = countService.findAllRecord(mobilephone);  
  424.         log.info("已发短信条数为:" +messageCount);  
  425.         if(messageCount < 5){  
  426.             /** 单个手机号发送短信 */  
  427.             if (!sendMessage(mobilephone, content, operId, tosend_time, sms_id,  
  428.                     backlist_filter, fbdword_filter, priority, valid_time)) {  
  429.                 result = "0";// 失败  
  430.             } else {  
  431.                 result = "1";// 成功  
  432.                 /** 发送一条短信,记录一条短信记录,为了方便之后的统计短信发送次数 */  
  433.                 count.setPhone(mobilephone);// 手机号码  
  434.                 count.setCaptcha(code);// 短信验证码  
  435.                 count.setSendTime(CommonUtil.getNowDate());// 短信发送时间  
  436.                 if(count != null){  
  437.                     countService.saveEntity(count);  
  438.                     log.info("短信验证码发送记录保存成功!");  
  439.                 }  
  440.             }  
  441.         }else{  
  442.             result = "2";//一个手机号码最多发送5条短信验证码  
  443.             log.info("该手机号码今天发送验证码过多");  
  444.         }  
  445.         HttpServletResponse response = WebContextUtil.getResponse();  
  446.         response.setContentType("application/json;charset=UTF-8");  
  447.         response.setHeader("Cache-Control""no-cache");  
  448.         PrintWriter out = response.getWriter();  
  449.         out.write(result.toString());  
  450.     }  
  451.       
  452.     /** 
  453.      * WebService客户端初始化 
  454.      *  
  455.      */  
  456.     public static boolean initClient() {  
  457.         /** 
  458.          * 判断客户端是否已经初始化 
  459.          */  
  460.         if (!SmsWebClient.enable()) {  
  461.             int ret = 0;  
  462.             try {  
  463.                 ret = SmsWebClient.init(url, userName, passWord);  
  464.                 if (ret == -1 || !SmsWebClient.enable()) {  
  465.                     log.info("短信平台接口初始化失败!");  
  466.                     return false;  
  467.                 }  
  468.                 log.info("短信平台接口初始化成功!" + ret + "-----");  
  469.             } catch (Exception ex) {  
  470.                 ex.printStackTrace();  
  471.                 log.info("短信平台接口初始化过程中异常!");  
  472.             }  
  473.         }  
  474.         return true;  
  475.     }  
  476.       
  477.     /** 
  478.      * 单个手机号码发送 
  479.      *  
  480.      * @param mobilephone 
  481.      *            手机号 
  482.      * @param content 
  483.      *            短信内容 
  484.      * @param operId 
  485.      *            操作用户的ID 
  486.      * @param tosend_time 
  487.      *            定时发送的发送时间 
  488.      * @param sms_id 
  489.      *            应用系统的短信ID 
  490.      * @param backlist_filter 
  491.      *            黑名单过滤 
  492.      * @param fbdword_filter 
  493.      *            禁止语过滤 
  494.      * @param priority 
  495.      *            优先级 
  496.      * @param valid_time 
  497.      *            短信有效时间 
  498.      */  
  499.     public static boolean sendMessage(java.lang.String mobilephone,  
  500.             java.lang.String content, int operId, java.lang.String tosend_time,  
  501.             int sms_id, short backlist_filter, short fbdword_filter,  
  502.             short priority, java.lang.String valid_time) {  
  503.         // 单个手机号码发送  
  504.         try {  
  505.             SmsReturnObj retObj = SmsWebClient.webSendMessage(mobilephone,  
  506.                     content, operId, tosend_time, sms_id, backlist_filter,  
  507.                     fbdword_filter, priority, valid_time);  
  508.             if (retObj.getReturnCode() != 1) {  
  509.                 log.info("短信发送失败,原因为:" + retObj.getReturnMsg());  
  510.                 return false;  
  511.             } else {  
  512.                 log.info("短信发送成功!返回结果为:" + retObj.getReturnMsg());  
  513.                 return true;  
  514.             }  
  515.         } catch (Exception ex) {  
  516.             ex.printStackTrace();  
  517.             log.info("短信发送过程发生异常!");  
  518.         }  
  519.         return true;  
  520.     }  
  521.       
  522.       
  523. }  


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


Demo下载链接: http://pan.baidu.com/s/1qWt1Qdm                                                                                          


    

=============================================================================

WebService实例3:利用WebService给手机发短信
实例说明   
通过编程方式实现短信息的发送对很多人来说是一件比较繁杂的事情,目前一般的解决方法是通过计算机和手机的连线,通过对手机编程的语言编写相关的手机短信息程序来实现,而这种方法对于一般人来说是很难达到的,因为此种方法不仅要有很多必备的硬件设备,也要懂得手机编程的相关知识。本实例将通过WebService技术发送手机短信,实例运行效果如图17.10所示。   
Java调用WebService接口实现发送手机短信验证码功能,java 手机验证码,WebService接口调用_第1张图片
关键技术   
本实例利用一个现有的可发送短信的WebService,这个 WebService是新浪网提供的可供用户直接调用的发送短消息的WebService。这个WebService的地址是http://smsinter.sina.com.cn/ws/smswebservice0101.wsdl。在
这个Service中,提供了一个发送短消息的方法sendXml,此方法的语法如下:  
string sendXml (carrier , userid , password , mobilenumber , content , msgtype )  
sendXml方法中的6个参数均为string类型,并且sendXml方法的返回值也是string类型。 
sendXml方法中的参数说明如表16.3所示。

Java调用WebService接口实现发送手机短信验证码功能,java 手机验证码,WebService接口调用_第2张图片
设计过程   
(1)新建一个网站,将其命名为MobileNote,默认主页为Default.aspx。在该页面中主要添加一个GridView 控件和一个Button控件,分别用来显示数据和执行查询操作。  
(2)Default.aspx页面中主要控件的类型、名称及用途如表17.3所示。
Java调用WebService接口实现发送手机短信验证码功能,java 手机验证码,WebService接口调用_第3张图片
(3)实例中单击Button1按钮完成短信发送,代码如下:
WebService实例3:利用WebService给手机发短信
=============================================================================


这个是方法是使用中国网建提供的SMS短信平台(http://sms.webchinese.cn)进行实现。 

所以在做这个的时候需要在中国网建SMS短信平台注册个用于测试的用户名,拿到用户名和密钥

 

需引用的jar包
commons-logging-1.1.1.jar
commons-httpclient-3.1.jar
commons-codec-1.4.jar

 

 

第一部分:SMS短信通编码接口

GBK编码发送接口地址:
http://gbk.sms.webchinese.cn/?Uid=本站用户名&Key=接口安全密码&smsMob=手机号码&smsText=短信容              
UTF-8编码发送接口地址:
http://utf8.sms.webchinese.cn/?Uid=本站用户名&Key=接口安全密码&smsMob=手机号码&smsText=短信内容
获取短信数量接口地址(UTF8):
http://sms.webchinese.cn/web_api/SMS/?Action=SMS_Num&Uid=本站用户名&Key=接口安全密码
获取短信数量接口地址(GBK):

http://sms.webchinese.cn/web_api/SMS/GBK/?Action=SMS_Num&Uid=本站用户名&Key=接口安全密码 

 

提示:HTTP调用URL接口时, 参数值必须URL编码后再调用

参数变量 说明
Gbk编码Url http://gbk.sms.webchinese.cn/
Utf-8编码Url http://utf8.sms.webchinese.cn/
Uid SMS短信通用户名(需注册)
Key 注册时填写的接口安全密码(可修改)
smsMob 目的手机号码(多个手机号请用半角逗号隔开)
smsText 短信内容,最多支持300个字,普通短信70个字/条,长短信64个字/条计费

提示:①、多个手机号请用半角,隔开如:13888888886,13888888887,1388888888 一次最多对100个手机发送。

      ②、短信内容支持长短信,最多300个字,普通短信66个字/条,长短信64个字/条计费 

短信发送后返回值 说明
-1 没有该用户账户
-2 密钥不正确
-3 短信数量不足
-11 该用户被禁用
-14 短信内容出现非法字符
-4 手机号格式不正确
-41 手机号码为空
-42 短信内容为空
-51 短信签名格式不正确接口签名格式为:【签名内容】
大于0 短信发送数量

注意:①、调用API接口,需登录中国网建SMS短信通平台,申请106网关发送,即发即到!
      ②、发送测试短信请勿输入:短信测试等词语,请直接提交您要发送的短信内容;
      ③、接口发送短信时请在内容后加签名:【XX公司或XX网名称】,否者会被屏蔽。
      ④、短信签名可在用户平台平台上设置,也可以在短信内容后,直接加入。

 

 

JAVA语言发送短信核心代码:

[java] view plain copy
  1. import java.io.UnsupportedEncodingException;  
  2. import org.apache.commons.httpclient.Header;  
  3. import org.apache.commons.httpclient.HttpClient;  
  4. import org.apache.commons.httpclient.NameValuePair;  
  5. import org.apache.commons.httpclient.methods.PostMethod;  
  6.   
  7. public class SendMsg_webchinese {  
  8.   
  9.     public static void main(String[] args)throws Exception{  
  10.   
  11.         HttpClient client = new HttpClient();  
  12.         PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn");   
  13.         post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在头文件中设置转码  
  14.         NameValuePair[] data ={   
  15.         new NameValuePair("Uid", "本站用户名"),  
  16.         new NameValuePair("Key", "接口安全密码"),  
  17.         new NameValuePair("smsMob","手机号码"),  
  18.         new NameValuePair("smsText","短信内容")  
  19.         };  
  20.         post.setRequestBody(data);  
  21.   
  22.         client.executeMethod(post);  
  23.         Header[] headers = post.getResponseHeaders();  
  24.         int statusCode = post.getStatusCode();  
  25.         System.out.println("statusCode:"+statusCode);  
  26.   
  27.         for(Header h : headers){  
  28.            System.out.println(h.toString());  
  29.         }  
  30.         String result = new String(post.getResponseBodyAsString().getBytes("gbk"));   
  31.         System.out.println(result);  
  32.   
  33.         post.releaseConnection();  
  34.     }  
  35. }  
[java] view plain copy
  1.   

你可能感兴趣的:(其他技术)