天天看點

Java調用WebService接口實作發送手機短信驗證碼功能,java 手機驗證碼,WebService接口調用

近來由于項目需要,需要用到手機短信驗證碼的功能,其中最主要的是用到了第三方提供的短信平台接口WebService用戶端接口,下面我把我在項目中用到的記錄一下,以便給大家提供個思路,由于本人的文采有限,還請大家見諒!

一:首先上幾張案例截圖,以便大家可以了解一下短信驗證碼的流程,這裡我在做的過程中也參考了很多網站的短信驗證碼,比如:58同城,汽車之家等。

1.點選擷取驗證碼之前的樣式:

Java調用WebService接口實作發送手機短信驗證碼功能,java 手機驗證碼,WebService接口調用

2.輸入正确的手機号後點選擷取驗證碼之後的樣式:

Java調用WebService接口實作發送手機短信驗證碼功能,java 手機驗證碼,WebService接口調用

3.如果手機号已經被注冊的樣式:

Java調用WebService接口實作發送手機短信驗證碼功能,java 手機驗證碼,WebService接口調用

4.如果一個手機号一天發送超過3次就提示不能發送:

Java調用WebService接口實作發送手機短信驗證碼功能,java 手機驗證碼,WebService接口調用

二:前台的注冊頁面的代碼: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. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  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>username</s: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>password</s: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>passwordRepeat</s: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>nickname</s: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>jbAddress</s: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>jbPhone</s: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>SmsCheckCodeTip</s: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>jbCredentialsName</s: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>jbCredentialsCode</s: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>jbCompanyName</s: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>jbSourceArea</s: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>checkNumTip</s: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.                             <input type="reset" value="重置" style="width:50px; height:24px;"/>  
  251.                         </td>  
  252.                     </tr>  
  253.                 </table>  
  254.             </s:form>  
  255.         </div>  
  256.     </div>  
  257.     <%@include file="/common/buttom.jspf"%>  
  258. </body>  
  259. </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. function sendMessage() {  
  7.     curCount = count;  
  8.     var jbPhone = $("#jbPhone").val();  
  9.     var jbPhoneTip = $("#jbPhoneTip").text();  
  10.     if (jbPhone != "") {  
  11.         if(jbPhoneTip == "√ 該手機号碼可以注冊,輸入正确" || jbPhoneTip == "√ 短信驗證碼已發到您的手機,請查收"){  
  12.             // 産生驗證碼  
  13.             for ( var i = 0; i < codeLength; i++) {  
  14.                 code += parseInt(Math.random() * 9).toString();  
  15.             }  
  16.             // 設定button效果,開始計時  
  17.             $("#btnSendCode").attr("disabled", "true");  
  18.             $("#btnSendCode").val("請在" + curCount + "秒内輸入驗證碼");  
  19.             InterValObj = window.setInterval(SetRemainTime, 1000); // 啟動計時器,1秒執行一次  
  20.             // 向背景發送處理資料  
  21.             $.ajax({  
  22.                 type: "POST", // 用POST方式傳輸  
  23.                 dataType: "text", // 資料格式:JSON  
  24.                 url: "UserAction_sms.action", // 目标位址  
  25.                 data: "jbPhone=" + jbPhone +"&code=" + code,  
  26.                 error: function (XMLHttpRequest, textStatus, errorThrown) {   
  27.                 },  
  28.                 success: function (data){   
  29.                     data = parseInt(data, 10);  
  30.                     if(data == 1){  
  31.                         $("#jbPhoneTip").html("<font color='#339933'>√ 短信驗證碼已發到您的手機,請查收</font>");  
  32.                     }else if(data == 0){  
  33.                         $("#jbPhoneTip").html("<font color='red'>× 短信驗證碼發送失敗,請重新發送</font>");  
  34.                     }else if(data == 2){  
  35.                         $("#jbPhoneTip").html("<font color='red'>× 該手機号碼今天發送驗證碼過多</font>");  
  36.                     }  
  37.                 }  
  38.             });  
  39.         }  
  40.     }else{  
  41.         $("#jbPhoneTip").html("<font color='red'>× 手機号碼不能為空</font>");  
  42.     }  
  43. }  
  44. //timer處理函數  
  45. function SetRemainTime() {  
  46.     if (curCount == 0) {                  
  47.         window.clearInterval(InterValObj);// 停止計時器  
  48.         $("#btnSendCode").removeAttr("disabled");// 啟用按鈕  
  49.         $("#btnSendCode").val("重新發送驗證碼");  
  50.         code = ""; // 清除驗證碼。如果不清除,過時間後,輸入收到的驗證碼依然有效  
  51.     }else {  
  52.         curCount--;  
  53.         $("#btnSendCode").val("請在" + curCount + "秒内輸入驗證碼");  
  54.     }  
  55. }  
  56. $(document).ready(function() {  
  57.     $("#SmsCheckCode").blur(function() {  
  58.         var SmsCheckCodeVal = $("#SmsCheckCode").val();  
  59.         // 向背景發送處理資料  
  60.         $.ajax({  
  61.             url : "UserAction_checkCode.action",   
  62.             data : {SmsCheckCode : SmsCheckCodeVal},   
  63.             type : "POST",   
  64.             dataType : "text",   
  65.             success : function(data) {  
  66.                 data = parseInt(data, 10);  
  67.                 if (data == 1) {  
  68.                     $("#SmsCheckCodeTip").html("<font color='#339933'>√ 短信驗證碼正确,請繼續</font>");  
  69.                 } else {  
  70.                     $("#SmsCheckCodeTip").html("<font color='red'>× 短信驗證碼有誤,請核實後重新填寫</font>");  
  71.                 }  
  72.             }  
  73.         });  
  74.     });  
  75. });  

四:驗證碼使用者名和手機号碼的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 = "<font color='red'>× 首字母不能為數字或者使用者名不能為空</font>";  
  11.         return false;  
  12.     } else if (username.length < 6 || username.length > 30) {  
  13.         document.getElementById("usernameTip").innerHTML = "<font color='red'>× 使用者名長度為6-30位字元</font>";  
  14.         return false;  
  15.     } else {  
  16.         document.getElementById("usernameTip").innerHTML = "<font color='#339933'>√ 使用者名合格</font>";  
  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("<font color='red'>× 該使用者名已經被注冊,請重新輸入</font>");  
  27.                 } else {  
  28.                     $("#usernameTip").html("<font color='#339933'>√ 該使用者名可以注冊,輸入正确</font>");  
  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 = "<font color='red'>× 密碼長度不能小于6位,大于30位</font>";  
  40.         return false;  
  41.     } else if (!isNaN(password)) {  
  42.         document.getElementById("passwordTip").innerHTML = "<font color='red'>× 密碼不能全是數字</font>";  
  43.         return false;  
  44.     } else {  
  45.         document.getElementById("passwordTip").innerHTML = "<font color='#339933'>√ 密碼合格</font>";  
  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 = "<font color='red'>× 兩次密碼輸入必須一緻</font>";  
  55.         return false;  
  56.     } else {  
  57.         document.getElementById("passwordRepeatTip").innerHTML = "<font color='#339933'>√ 密碼輸入一緻</font>";  
  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 = "<font color='red'>× 姓名不能為空</font>";  
  66.         return false;  
  67.     } else {  
  68.         document.getElementById("nicknameTip").innerHTML = "<font color='#339933'>√ 姓名輸入正确</font>";  
  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 = "<font color='red'>× 手機号碼不能為空</font>";  
  78.         return false;  
  79.     } else if(trim(jbPhone) != ""){  
  80.         if(!re.test(jbPhone)){  
  81.             document.getElementById("jbPhoneTip").innerHTML = "<font color='red'>× 請輸入有效的手機号碼</font>";  
  82.             return false;  
  83.         }else{  
  84.             document.getElementById("jbPhoneTip").innerHTML = "<font color='#339933'>√ 手機号碼輸入正确</font>";  
  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("<font color='red'>× 該手機号碼已經被注冊,請重新輸入</font>");  
  95.                     } else {  
  96.                         $("#jbPhoneTip").html("<font color='#339933'>√ 該手機号碼可以注冊,輸入正确</font>");  
  97.                     }  
  98.                 }  
  99.             });  
  100.             return true;  
  101.         }  
  102.     }  
  103. }  
  104. // 證件号碼  
  105. function checkjbCredentialsCode() {  
  106.     var jbCredentialsCode = document.form1.jbCredentialsCode.value;  
  107.     var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;   
  108.     if (trim(jbCredentialsCode) == "") {  
  109.         document.getElementById("jbCredentialsCodeTip").innerHTML = "<font color='red'>× 證件号碼不能為空</font>";  
  110.         return false;  
  111.     } else if(trim(jbCredentialsCode) != ""){  
  112.         if(!reg.test(jbCredentialsCode)){  
  113.             document.getElementById("jbCredentialsCodeTip").innerHTML = "<font color='red'>× 請輸入合法的證件号碼</font>";  
  114.             return false;  
  115.         }else{  
  116.             document.getElementById("jbCredentialsCodeTip").innerHTML = "<font color='#339933'>√ 證件号碼輸入正确</font>";  
  117.             // 向背景發送處理資料  
  118.             $.ajax({  
  119.                 url : "UserAction_checkCredentialsCode.action",// 目标位址  
  120.                 data : {jbCredentialsCode : jbCredentialsCode}, // 目标參數  
  121.                 type : "POST", // 用POST方式傳輸  
  122.                 dataType : "text", // 資料格式:text  
  123.                 success : function(data) {  
  124.                     data = parseInt(data, 10);  
  125.                     if (data != 0) {  
  126.                         $("#jbCredentialsCodeTip").html("<font color='red'>× 該證件号碼已經被注冊,請重新輸入</font>");  
  127.                     } else {  
  128.                         $("#jbCredentialsCodeTip").html("<font color='#339933'>√ 該證件号碼可以注冊,輸入正确</font>");  
  129.                     }  
  130.                 }  
  131.             });  
  132.             return true;  
  133.         }  
  134.     }  
  135. }  
  136. // 所在地區  
  137. function checkjbSourceArea() {  
  138.     var jbSourceArea = document.form1.jbSourceArea.value;  
  139.     if (trim(jbSourceArea) == "") {  
  140.         document.getElementById("jbSourceAreaTip").innerHTML = "<font color='red'>× 請選擇所在地區</font>";  
  141.         return false;  
  142.     } else {  
  143.         document.getElementById("jbSourceAreaTip").innerHTML = "<font color='#339933'>√ 所在地區選擇正确</font>";  
  144.         return true;  
  145.     }  
  146. }  
  147. // 驗證碼  
  148. function checkNumber() {  
  149.     var checkNum = document.form1.checkNum.value;  
  150.     if (trim(checkNum) == "") {  
  151.         document.getElementById("checkNumTip").innerHTML = "<font color='red'>× 驗證碼不能為空</font>";  
  152.         return false;  
  153.     } else {  
  154.         document.getElementById("checkNumTip").innerHTML = "<font color='#339933'>√ 驗證碼合格</font>";  
  155.         // 向背景發送處理資料  
  156.         $.ajax({  
  157.             url : "UserAction_checkNum.action",// 目标位址  
  158.             data : {checkNum : checkNum}, // 目标參數  
  159.             type : "POST", // 用POST方式傳輸  
  160.             dataType : "text", // 資料格式:text  
  161.             success : function(data) {  
  162.                 data = parseInt(data, 10);  
  163.                 if (data != 0) {  
  164.                     $("#checkNumTip").html("<font color='red'>× 驗證碼錯誤</font>");  
  165.                 } else {  
  166.                     $("#checkNumTip").html("<font color='#339933'>√ 驗證碼正确</font>");  
  167.                 }  
  168.             }  
  169.         });  
  170.         return true;  
  171.     }  
  172. }  

五:背景action的代碼:UserAction.java(這裡隻是調用了我們的第三方給提供的用戶端代碼的發送短信的方法,如果是調用其他的短信平台,可以換成他們的發送短信的方法,這裡隻是給大家做個參考)

[java] view plain copy

  1. package cn.gov.csrc.base.systemmanager.action;  
  2. import java.io.IOException;  
  3. import java.io.PrintWriter;  
  4. import java.util.List;  
  5. import javax.annotation.Resource;  
  6. import javax.servlet.http.HttpServletResponse;  
  7. import org.apache.log4j.Logger;  
  8. import org.apache.struts2.convention.annotation.Action;  
  9. import org.apache.struts2.convention.annotation.Result;  
  10. import org.apache.struts2.convention.annotation.Results;  
  11. import org.springframework.context.annotation.Scope;  
  12. import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;  
  13. import org.springframework.security.core.context.SecurityContextHolder;  
  14. import org.springframework.stereotype.Controller;  
  15. import cn.gov.csrc.base.action.BaseAction;  
  16. import cn.gov.csrc.base.log.service.LogService;  
  17. import cn.gov.csrc.base.report.util.CommonUtil;  
  18. import cn.gov.csrc.base.report.util.Env;  
  19. import cn.gov.csrc.base.systemmanager.model.Count;  
  20. import cn.gov.csrc.base.systemmanager.model.User;  
  21. import cn.gov.csrc.base.systemmanager.service.CountService;  
  22. import cn.gov.csrc.base.systemmanager.service.UserService;  
  23. import cn.gov.csrc.base.util.WebContextUtil;  
  24. import com.sms.webservice.client.SmsReturnObj;  
  25. import com.sms.webservice.client.SmsWebClient;  
  26. @Controller()  
  27. @Scope("prototype")  
  28. @Results({  
  29.         @Result(name = "success", location = "/statics/report.jsp"),  
  30.         @Result(name = "modifyPassword", location = "/statics/modifyPassword.jsp")  
  31.         })  
  32. public class UserAction extends BaseAction<User> {  
  33.     private static final long serialVersionUID = 1214696686677691191L;  
  34.     private static Logger log = Logger.getLogger(UserAction.class);  
  35.     private static final String url = Env.getInstance().getProperty("url");  
  36.     private static final String userName = Env.getInstance().getProperty(  
  37.             "username");  
  38.     private static final String passWord = Env.getInstance().getProperty(  
  39.             "password");  
  40.     private Integer id;  
  41.     private String username;// 使用者名  
  42.     private String password;// 密碼  
  43.     private String passwordRepeat;// 确認密碼  
  44.     private String jbPhone;//手機号碼  
  45.     private String jbCredentialsCode;//身份證号碼  
  46.     private String checkNum;//圖檔驗證碼  
  47.     private String newPassword;  
  48.     private String confirmPassword;  
  49.     private Integer[] ownRoleIds;  
  50.     private UserService userService;  
  51.     private CountService countService;  
  52.     private LogService logService;  
  53.     private Count count = new Count();  
  54.     public Integer getId() {  
  55.         return id;  
  56.     }  
  57.     public void setId(Integer id) {  
  58.         this.id = id;  
  59.     }  
  60.     public String getUsername() {  
  61.         return username;  
  62.     }  
  63.     public void setUsername(String username) {  
  64.         this.username = username;  
  65.     }  
  66.     public String getPassword() {  
  67.         return password;  
  68.     }  
  69.     public void setPassword(String password) {  
  70.         this.password = password;  
  71.     }  
  72.     public String getPasswordRepeat() {  
  73.         return passwordRepeat;  
  74.     }  
  75.     public void setPasswordRepeat(String passwordRepeat) {  
  76.         this.passwordRepeat = passwordRepeat;  
  77.     }  
  78.     public String getJbPhone() {  
  79.         return jbPhone;  
  80.     }  
  81.     public void setJbPhone(String jbPhone) {  
  82.         this.jbPhone = jbPhone;  
  83.     }  
  84.     public String getJbCredentialsCode() {  
  85.         return jbCredentialsCode;  
  86.     }  
  87.     public void setJbCredentialsCode(String jbCredentialsCode) {  
  88.         this.jbCredentialsCode = jbCredentialsCode;  
  89.     }  
  90.     public String getCheckNum() {  
  91.         return checkNum;  
  92.     }  
  93.     public void setCheckNum(String checkNum) {  
  94.         this.checkNum = checkNum;  
  95.     }  
  96.     public Integer[] getOwnRoleIds() {  
  97.         return ownRoleIds;  
  98.     }  
  99.     public void setOwnRoleIds(Integer[] ownRoleIds) {  
  100.         this.ownRoleIds = ownRoleIds;  
  101.     }  
  102.     public String getNewPassword() {  
  103.         return newPassword;  
  104.     }  
  105.     public void setNewPassword(String newPassword) {  
  106.         this.newPassword = newPassword;  
  107.     }  
  108.     public String getConfirmPassword() {  
  109.         return confirmPassword;  
  110.     }  
  111.     public void setConfirmPassword(String confirmPassword) {  
  112.         this.confirmPassword = confirmPassword;  
  113.     }  
  114.     @Resource  
  115.     public void setUserService(UserService userService) {  
  116.         this.userService = userService;  
  117.     }  
  118.     public UserService getUserService() {  
  119.         return userService;  
  120.     }  
  121.     @Resource  
  122.     public void setCountService(CountService countService) {  
  123.         this.countService = countService;  
  124.     }  
  125.     public CountService getCountService() {  
  126.         return countService;  
  127.     }  
  128.     public LogService getLogService() {  
  129.         return logService;  
  130.     }  
  131.     @Resource  
  132.     public void setLogService(LogService logService) {  
  133.         this.logService = logService;  
  134.     }  
  135.     public Count getCount() {  
  136.         return count;  
  137.     }  
  138.     public void setCount(Count count) {  
  139.         this.count = count;  
  140.     }  
  141.     public void prepareToUpdatePage() {  
  142.         model = userService.getEntity(id);  
  143.     }  
  144.     @Action(value = "UserAction_login")  
  145.     public String login() {  
  146.         Object u = SecurityContextHolder.getContext().getAuthentication().getPrincipal();  
  147.         if (u instanceof User && u != null) {  
  148.             WebContextUtil.getSession().setAttribute("user", u);  
  149.             User user = (User)u;  
  150.             //使用資料庫表TBL_BASE_LOG添加使用者登入的日志資訊  
  151.             logService.saveTblBaseLog(WebContextUtil.getRequest(),"目前操作人【"+user.getNickname()+"】登入系統");  
  152.         } else {  
  153.             // 防止繞過登陸頁面直接執行Action  
  154.             return "login";  
  155.         }  
  156.         return SUCCESS;  
  157.     }  
  158.     @Action(value = "UserAction_updateUser")  
  159.     public String updateUser() {  
  160.         if (!newPassword.equals(confirmPassword)) {  
  161.             this.setMessage("新密碼與确認密碼不一緻!");  
  162.             return "modifyPassword";  
  163.         }  
  164.         User u = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();  
  165.         MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("md5");  
  166.         String psw = encoder.encodePassword(newPassword, null);  
  167.         userService.modifyPassword(u, psw);  
  168.         this.setMessage("儲存成功!");  
  169.         return "modifyPassword";  
  170.     }  
  171.     @Action(value = "UserAction_checkUserName")  
  172.     public void checkUserName(){  
  173.         String result = "0";  
  174.         try {  
  175.             List<User> list = userService.findUserByUserName(username);  
  176.             if(list != null && list.size() > 0){  
  177.                 result = "1";  
  178.             }else{  
  179.                 result = "0";  
  180.             }  
  181.             HttpServletResponse response = WebContextUtil.getResponse();  
  182.             response.setContentType("application/json;charset=UTF-8");  
  183.             response.setHeader("Cache-Control", "no-cache");  
  184.             PrintWriter out = response.getWriter();  
  185.             out.write(result.toString());  
  186.         } catch (IOException e) {  
  187.             throw new RuntimeException("驗證身份證号碼出錯", e);  
  188.         }  
  189.     }  
  190.     @Action(value = "UserAction_checkPassWord")  
  191.     public void checkPassWord() throws Exception {  
  192.         String result = "0";  
  193.         MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("md5");  
  194.         String pwd = encoder.encodePassword(password, null);  
  195.         List<User> user = userService.findUserByPassWord(pwd);  
  196.         if (user != null && user.size() > 0) {  
  197.             result = "1";  
  198.         }else{  
  199.             result = "0";  
  200.         }  
  201.         HttpServletResponse response = WebContextUtil.getResponse();  
  202.         response.setContentType("application/json;charset=UTF-8");  
  203.         response.setHeader("Cache-Control", "no-cache");  
  204.         PrintWriter out = response.getWriter();  
  205.         out.write(result.toString());  
  206.     }  
  207.     @Action(value = "UserAction_checkPhone")  
  208.     public void checkPhone(){  
  209.         String result = "0";  
  210.         try {  
  211.             List<User> list = userService.findUserByPhone(jbPhone);  
  212.             if(list != null && list.size() > 0){  
  213.                 result = "1";  
  214.             }else{  
  215.                 result = "0";  
  216.             }  
  217.             HttpServletResponse response = WebContextUtil.getResponse();  
  218.             response.setContentType("application/json;charset=UTF-8");  
  219.             response.setHeader("Cache-Control", "no-cache");  
  220.             PrintWriter out = response.getWriter();  
  221.             out.write(result.toString());  
  222.         } catch (IOException e) {  
  223.             throw new RuntimeException("驗證手機号碼出錯", e);  
  224.         }  
  225.     }  
  226.     @Action(value = "UserAction_checkCredentialsCode")  
  227.     public void checkCredentialsCode(){  
  228.         String result = "0";  
  229.         try {  
  230.             List<User> list = userService.findUserByCredentialsCode(jbCredentialsCode);  
  231.             if(list != null && list.size() > 0){  
  232.                 result = "1";  
  233.             }else{  
  234.                 result = "0";  
  235.             }  
  236.             HttpServletResponse response = WebContextUtil.getResponse();  
  237.             response.setContentType("application/json;charset=UTF-8");  
  238.             response.setHeader("Cache-Control", "no-cache");  
  239.             PrintWriter out = response.getWriter();  
  240.             out.write(result.toString());  
  241.         } catch (IOException e) {  
  242.             throw new RuntimeException("驗證身份證号碼出錯", e);  
  243.         }  
  244.     }  
  245.     @Action(value = "UserAction_checkNum")  
  246.     public void checkNum(){  
  247.         try {  
  248.             String result = "0";  
  249.             String check_number_key = (String)WebContextUtil.getSession().getAttribute("CHECK_NUMBER_KEY");  
  250.             if(checkNum != check_number_key && !checkNum.equals(check_number_key)){  
  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.     @Action(value = "UserAction_checkCode")  
  265.     public void checkCode() throws Exception{  
  266.         String result = "0";  
  267.         String SmsCheckCode = WebContextUtil.getRequest().getParameter("SmsCheckCode");  
  268.         String code = (String) WebContextUtil.getSession().getAttribute("code");  
  269.         try {  
  270.             if(SmsCheckCode != code && !SmsCheckCode.equals(code)){  
  271.                 result = "0";  
  272.             }else{  
  273.                 result = "1";  
  274.             }  
  275.         } catch (Exception e) {  
  276.             throw new RuntimeException("短信驗證失敗", e);  
  277.         }  
  278.         HttpServletResponse response = WebContextUtil.getResponse();  
  279.         response.setContentType("application/json;charset=UTF-8");  
  280.         response.setHeader("Cache-Control", "no-cache");  
  281.         PrintWriter out = response.getWriter();  
  282.         out.write(result.toString());  
  283.     }  
  284.     @Action(value = "UserAction_sms")  
  285.     public void sms() throws Exception {  
  286.         String result = "0";  
  287.         String jbPhone = WebContextUtil.getRequest().getParameter("jbPhone");  
  288.         String code = WebContextUtil.getRequest().getParameter("code");  
  289.         WebContextUtil.getSession().setAttribute("code", code);  
  290.         if(!initClient()) {  
  291.             return;  
  292.         }  
  293.         // 手機号碼  
  294.         String mobilephone = jbPhone;  
  295.         // 短信内容+随機生成的6位短信驗證碼  
  296.         String content = "根據中國證監會舉報中心委托,特向您發送此條短信。您的注冊驗證碼為:" + code;  
  297.         // 操作使用者的ID  
  298.         Integer operId = Integer.parseInt(Env.getInstance().getProperty("operId"));  
  299.         // 定時發送的的發送時間(預設為空,如果即時發送,填空)  
  300.         String tosend_time = "";  
  301.         // 應用系統的短信ID,使用者查詢該短信的狀态報告(預設為0,即不需查詢短信的狀态報告)  
  302.         int sms_id = 0;  
  303.         // 黑名單過濾(0:不需要黑名單過濾,1:需要黑名單過濾,預設為0)  
  304.         short backlist_filter = 0;  
  305.         // 禁止語過濾(0:不需要禁止語過濾,1:需要禁止語過濾,預設為0)  
  306.         short fbdword_filter = 0;  
  307.         // 優先級(值越大優先級越高,0:普通,1,:優先,2:最高,預設為0)  
  308.         short priority = 0;  
  309.         // 短信有效時間(格式為:YYYY-MM-DD HH:mm:ss目前為空)  
  310.         String valid_time = "";  
  311.         int messageCount = countService.findAllRecord(mobilephone);  
  312.         log.info("已發短信條數為:" +messageCount);  
  313.         if(messageCount < 5){  
  314.             if (!sendMessage(mobilephone, content, operId, tosend_time, sms_id,  
  315.                     backlist_filter, fbdword_filter, priority, valid_time)) {  
  316.                 result = "0";// 失敗  
  317.             } else {  
  318.                 result = "1";// 成功  
  319.                 count.setPhone(mobilephone);// 手機号碼  
  320.                 count.setCaptcha(code);// 短信驗證碼  
  321.                 count.setSendTime(CommonUtil.getNowDate());// 短信發送時間  
  322.                 if(count != null){  
  323.                     countService.saveEntity(count);  
  324.                     log.info("短信驗證碼發送記錄儲存成功!");  
  325.                 }  
  326.             }  
  327.         }else{  
  328.             result = "2";//一個手機号碼最多發送5條短信驗證碼  
  329.             log.info("該手機号碼今天發送驗證碼過多");  
  330.         }  
  331.         HttpServletResponse response = WebContextUtil.getResponse();  
  332.         response.setContentType("application/json;charset=UTF-8");  
  333.         response.setHeader("Cache-Control", "no-cache");  
  334.         PrintWriter out = response.getWriter();  
  335.         out.write(result.toString());  
  336.     }  
  337.     public static boolean initClient() {  
  338.         if (!SmsWebClient.enable()) {  
  339.             int ret = 0;  
  340.             try {  
  341.                 ret = SmsWebClient.init(url, userName, passWord);  
  342.                 if (ret == -1 || !SmsWebClient.enable()) {  
  343.                     log.info("短信平台接口初始化失敗!");  
  344.                     return false;  
  345.                 }  
  346.                 log.info("短信平台接口初始化成功!" + ret + "-----");  
  347.             } catch (Exception ex) {  
  348.                 ex.printStackTrace();  
  349.                 log.info("短信平台接口初始化過程中異常!");  
  350.             }  
  351.         }  
  352.         return true;  
  353.     }  
  354.     public static boolean sendMessage(java.lang.String mobilephone,  
  355.             java.lang.String content, int operId, java.lang.String tosend_time,  
  356.             int sms_id, short backlist_filter, short fbdword_filter,  
  357.             short priority, java.lang.String valid_time) {  
  358.         // 單個手機号碼發送  
  359.         try {  
  360.             SmsReturnObj retObj = SmsWebClient.webSendMessage(mobilephone,  
  361.                     content, operId, tosend_time, sms_id, backlist_filter,  
  362.                     fbdword_filter, priority, valid_time);  
  363.             if (retObj.getReturnCode() != 1) {  
  364.                 log.info("短信發送失敗,原因為:" + retObj.getReturnMsg());  
  365.                 return false;  
  366.             } else {  
  367.                 log.info("短信發送成功!傳回結果為:" + retObj.getReturnMsg());  
  368.                 return true;  
  369.             }  
  370.         } catch (Exception ex) {  
  371.             ex.printStackTrace();  
  372.             log.info("短信發送過程發生異常!");  
  373.         }  
  374.         return true;  
  375.     }  
  376. }  

六:具體的短信接口demo到這裡下,這裡你下載下傳了也不能成功的發送短信,因為你必須要短信平台商給你提供:url,userName,passWord,operId,以及短信平台商還要綁定你的外網ip位址,這樣才能真正的發送短信。

Demo下載下傳連結: http://pan.baidu.com/s/1qWt1Qdm                                                                                          

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

WebService執行個體3:利用WebService給手機發短信 執行個體說明    通過程式設計方式實作短資訊的發送對很多人來說是一件比較繁雜的事情,目前一般的解決方法是通過計算機和手機的連線,通過對手機程式設計的語言編寫相關的手機短資訊程式來實作,而這種方法對于一般人來說是很難達到的,因為此種方法不僅要有很多必備的硬體裝置,也要懂得手機程式設計的相關知識。本執行個體将通過WebService技術發送手機短信,執行個體運作效果如圖17.10所示。   

Java調用WebService接口實作發送手機短信驗證碼功能,java 手機驗證碼,WebService接口調用

關鍵技術    本執行個體利用一個現有的可發送短信的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接口調用

設計過程    (1)建立一個網站,将其命名為MobileNote,預設首頁為Default.aspx。在該頁面中主要添加一個GridView 控件和一個Button控件,分别用來顯示資料和執行查詢操作。   (2)Default.aspx頁面中主要控件的類型、名稱及用途如表17.3所示。

Java調用WebService接口實作發送手機短信驗證碼功能,java 手機驗證碼,WebService接口調用

(3)執行個體中單擊Button1按鈕完成短信發送,代碼如下:

Java調用WebService接口實作發送手機短信驗證碼功能,java 手機驗證碼,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. public class SendMsg_webchinese {  
  7.     public static void main(String[] args)throws Exception{  
  8.         HttpClient client = new HttpClient();  
  9.         PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn");   
  10.         post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在頭檔案中設定轉碼  
  11.         NameValuePair[] data ={   
  12.         new NameValuePair("Uid", "本站使用者名"),  
  13.         new NameValuePair("Key", "接口安全密碼"),  
  14.         new NameValuePair("smsMob","手機号碼"),  
  15.         new NameValuePair("smsText","短信内容")  
  16.         };  
  17.         post.setRequestBody(data);  
  18.         client.executeMethod(post);  
  19.         Header[] headers = post.getResponseHeaders();  
  20.         int statusCode = post.getStatusCode();  
  21.         System.out.println("statusCode:"+statusCode);  
  22.         for(Header h : headers){  
  23.            System.out.println(h.toString());  
  24.         }  
  25.         String result = new String(post.getResponseBodyAsString().getBytes("gbk"));   
  26.         System.out.println(result);  
  27.         post.releaseConnection();  
  28.     }  
  29. }  

[java] view plain copy

繼續閱讀