发送短信

来源:互联网 发布:php中split函数用法 编辑:程序博客网 时间:2024/05/29 11:33

上 code:

sendSMS.jsp

<%@ page contentType="text/html;charset=UTF-8" %><%@ include file="/webpage/include/taglib.jsp"%><!DOCTYPE html><html><head>    <meta charset="utf-8">    <meta name="decorator" content="default"/>      <!-- SUMMERNOTE --> <link href="${ctxStatic}/summernote/summernote.css" rel="stylesheet"> <link href="${ctxStatic}/summernote/summernote-bs3.css" rel="stylesheet"> <script src="${ctxStatic}/summernote/summernote.min.js"></script> <script src="${ctxStatic}/summernote/summernote-zh-CN.js"></script></head><body class="gray-bg">    <div class="wrapper wrapper-content">        <div class="row">            <div class="col-sm-12 animated fadeInRight">                <div class="mail-box-header">                    <div class="pull-right tooltip-demo">                       <button type="button" class="btn btn-white  btn-sm" onclick="sendSMS()"> <i class="fa fa-pencil"></i> 发送短信</button>                    </div>                    <h2>                    发短信                </h2>                </div>                               <div class="mail-box">                    <div class="mail-body"><form:form id="inputForm" modelAttribute="mailBox" action="${ctx}/tools/sms/send" method="post" class="form-horizontal">                            <div class="form-group">                                <label class="col-sm-2 control-label"><font color="red">*</font>发送到:</label>                                <div class="col-sm-8">                                    <input type="text" placeholder="输入多个手机号码请用英文符号,隔开" id="tels" name="tels"  class="form-control" value="">                                </div>                            </div>                                                         <div class="form-group">                                <label class="col-sm-2 control-label"><font color="red">*</font>短信内容:</label>                                <div class="col-sm-8">                                     <textarea id="content" name="content"  class="form-control" required="" aria-required="true">                                                                                                               </textarea>                                </div>                            </div>                                                                </form:form>                    </div>                    <div class="mail-body text-right tooltip-demo">                                         <button type="button" class="btn btn-primary  btn-sm" onclick="sendSMS()"> <i class="fa fa-reply"></i> 发送</button>                    </div>                    <div class="clearfix"></div>                </div>            </div>        </div>    </div>    <script>        $(document).ready(function () {            $('.i-checks').iCheck({                checkboxClass: 'icheckbox_square-green',                radioClass: 'iradio_square-green',            });        });        var edit = function () {            $('.click2edit').summernote({                focus: true            });        };        var save = function () {            var aHTML = $('.click2edit').code(); //save HTML If you need(aHTML: array).            $('.click2edit').destroy();        };        function sendSMS(){            if($("#tels").val()==''){            top.layer.alert('手机号不能为空!', {icon: 0});            return;            }var index = layer.load(1, {    shade: [0.3,'#fff'] //0.1透明度的白色背景});$("#inputForm").submit();    }    </script></body></html>

sendSMSResult.jsp

<%@ page contentType="text/html;charset=UTF-8" %><%@ include file="/webpage/include/taglib.jsp"%><!DOCTYPE html><html><head>    <meta charset="utf-8">    <meta name="decorator" content="default"/>      <!-- SUMMERNOTE --> <link href="${ctxStatic}/summernote/summernote.css" rel="stylesheet"> <link href="${ctxStatic}/summernote/summernote-bs3.css" rel="stylesheet"> <script src="${ctxStatic}/summernote/summernote.min.js"></script> <script src="${ctxStatic}/summernote/summernote-zh-CN.js"></script></head><body class="gray-bg">    <div class="lock-word animated fadeInDown">    </div>    <div class="middle-box text-center lockscreen animated fadeInDown" style="width:400px">        <div>            <div class="m-b-md">                <img alt="image" style="width:150px;"class="img-circle circle-border" src="${ctxStatic}/images/success.jpg">            </div>             <sys:message hideType="0" content="${result}"/>                        <form class="m-t" role="form" action="index.html">                <a href="${ctx}/tools/sms" class="btn btn-primary block full-width">返回</a>            </form>        </div>    </div></body></html>
controller

package com.jeeplus.modules.tools.web;import java.io.IOException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import com.jeeplus.common.sms.SMSUtils;import com.jeeplus.common.web.BaseController;import com.jeeplus.modules.sys.entity.SystemConfig;import com.jeeplus.modules.sys.service.SystemConfigService;/** * 发送短信 * @author lgf * @version 2016-01-07 */@Controller@RequestMapping(value = "${adminPath}/tools/sms")public class SMSController extends BaseController {@Autowiredprivate SystemConfigService systemConfigService;/** * 打开短信页面 */@RequestMapping(value = {"index", ""})public String index( HttpServletRequest request, HttpServletResponse response, Model model) {return "modules/tools/sendSMS";}/** * 发送短信 */@RequestMapping("send")public String send(String tels,  HttpServletResponse response, String content, Model model) throws Exception {SystemConfig config = systemConfigService.get("1");String result = "";try{String resultCode = SMSUtils.send(config.getSmsName(),config.getSmsPassword(), tels, content);if (!resultCode.equals("100")) {result = "短信发送失败,错误代码:"+resultCode+",请 联系管理员。";}else{result = "短信发送成功";}} catch (IOException e) {result = "因未知原因导致短信发送失败,请联系管理员。";}model.addAttribute("result", result);return "modules/tools/sendSMSResult";}}

工具类

package com.jeeplus.common.sms;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;import com.jeeplus.common.security.Digests;/*功能:企信通PHP HTTP接口 发送短信修改日期:2014-03-19说明:http://api.cnsms.cn/?ac=send&uid=用户账号&pwd=MD5位32密码&mobile=号码&content=内容状态:100 发送成功101 验证失败102 短信不足103 操作失败104 非法字符105 内容过多106 号码过多107 频率过快108 号码内容空109 账号冻结110 禁止频繁单条发送111 系统暂定发送112 号码不正确120 系统升级*/public class SMSUtils {//发送短信,uid,pwd,参数值请向企信通申请, tel:发送的手机号, content:发送的内容public static String send(String uid, String pwd, String tel, String content) throws IOException {// 创建StringBuffer对象用来操作字符串StringBuffer sb = new StringBuffer("http://api.cnsms.cn/?");// 向StringBuffer追加用户名sb.append("ac=send&uid="+uid);//在此申请企信通uid,并进行配置用户名// 向StringBuffer追加密码(密码采用MD5 32位 小写)sb.append("&encode=utf8");// 向StringBuffer追加密码(密码采用MD5 32位 小写)sb.append("&pwd="+Digests.string2MD5(pwd));//在此申请企信通uid,并进行配置密码// 向StringBuffer追加手机号码sb.append("&mobile="+tel);// 向StringBuffer追加消息内容转URL标准码sb.append("&content="+URLEncoder.encode(content,"utf8"));// 创建url对象URL url = new URL(sb.toString());// 打开url连接HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 设置url请求方式 ‘get’ 或者 ‘post’connection.setRequestMethod("POST");// 发送BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));// 返回发送结果String inputline = in.readLine();return inputline;}}
相关的类

/** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */package com.jeeplus.modules.sys.entity;import org.hibernate.validator.constraints.Length;import com.jeeplus.common.persistence.DataEntity;import com.jeeplus.common.utils.excel.annotation.ExcelField;/** * 系统配置Entity * @author liugf * @version 2016-02-07 */public class SystemConfig extends DataEntity<SystemConfig> {private static final long serialVersionUID = 1L;private String smtp;// 邮箱服务器地址private String port;// 邮箱服务器端口private String mailName;// 系统邮箱地址private String mailPassword;// 系统邮箱密码private String openSSL;// 开启SSLprivate String smsName;// 短信用户名private String smsPassword;// 短信密码private boolean test = false;public SystemConfig() {super();}public SystemConfig(String id){super(id);}@Length(min=0, max=64, message="邮箱服务器地址长度必须介于 0 和 64 之间")@ExcelField(title="邮箱服务器地址", align=2, sort=1)public String getSmtp() {return smtp;}public void setSmtp(String smtp) {this.smtp = smtp;}@Length(min=0, max=64, message="邮箱服务器端口长度必须介于 0 和 64 之间")@ExcelField(title="邮箱服务器端口", align=2, sort=2)public String getPort() {return port;}public void setPort(String port) {this.port = port;}@Length(min=0, max=64, message="系统邮箱地址长度必须介于 0 和 64 之间")@ExcelField(title="系统邮箱地址", align=2, sort=3)public String getMailName() {return mailName;}public void setMailName(String mailName) {this.mailName = mailName;}@Length(min=0, max=64, message="系统邮箱密码长度必须介于 0 和 64 之间")@ExcelField(title="系统邮箱密码", align=2, sort=4)public String getMailPassword() {return mailPassword;}public void setMailPassword(String mailPassword) {this.mailPassword = mailPassword;}@Length(min=0, max=64, message="短信用户名长度必须介于 0 和 64 之间")@ExcelField(title="短信用户名", align=2, sort=5)public String getSmsName() {return smsName;}public void setSmsName(String smsName) {this.smsName = smsName;}@Length(min=0, max=64, message="短信密码长度必须介于 0 和 64 之间")@ExcelField(title="短信密码", align=2, sort=6)public String getSmsPassword() {return smsPassword;}public void setSmsPassword(String smsPassword) {this.smsPassword = smsPassword;}public void setTest(boolean test) {this.test = test;}public boolean isTest() {return test;}public String getOpenSSL() {return openSSL;}public void setOpenSSL(String openSSL) {this.openSSL = openSSL;}}


/** * Copyright (c) 2005-2012 springside.org.cn */package com.jeeplus.common.security;import java.io.IOException;import java.io.InputStream;import java.security.GeneralSecurityException;import java.security.MessageDigest;import java.security.SecureRandom;import org.apache.commons.lang3.Validate;import com.jeeplus.common.utils.Exceptions;/** * 支持SHA-1/MD5消息摘要的工具类. *  * 返回ByteSource,可进一步被编码为Hex, Base64或UrlSafeBase64 *  * @author calvin */public class Digests {private static final String SHA1 = "SHA-1";private static final String MD5 = "MD5";private static SecureRandom random = new SecureRandom();/** * 对输入字符串进行md5散列. */public static byte[] md5(byte[] input) {return digest(input, MD5, null, 1);}public static byte[] md5(byte[] input, int iterations) {return digest(input, MD5, null, iterations);}/** * 对输入字符串进行sha1散列. */public static byte[] sha1(byte[] input) {return digest(input, SHA1, null, 1);}public static byte[] sha1(byte[] input, byte[] salt) {return digest(input, SHA1, salt, 1);}public static byte[] sha1(byte[] input, byte[] salt, int iterations) {return digest(input, SHA1, salt, iterations);}/** * 对字符串进行散列, 支持md5与sha1算法. */private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {try {MessageDigest digest = MessageDigest.getInstance(algorithm);if (salt != null) {digest.update(salt);}byte[] result = digest.digest(input);for (int i = 1; i < iterations; i++) {digest.reset();result = digest.digest(result);}return result;} catch (GeneralSecurityException e) {throw Exceptions.unchecked(e);}}/** * 生成随机的Byte[]作为salt. *  * @param numBytes byte数组的大小 */public static byte[] generateSalt(int numBytes) {Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);byte[] bytes = new byte[numBytes];random.nextBytes(bytes);return bytes;}/** * 对文件进行md5散列. */public static byte[] md5(InputStream input) throws IOException {return digest(input, MD5);}/** * 对文件进行sha1散列. */public static byte[] sha1(InputStream input) throws IOException {return digest(input, SHA1);}private static byte[] digest(InputStream input, String algorithm) throws IOException {try {MessageDigest messageDigest = MessageDigest.getInstance(algorithm);int bufferLength = 8 * 1024;byte[] buffer = new byte[bufferLength];int read = input.read(buffer, 0, bufferLength);while (read > -1) {messageDigest.update(buffer, 0, read);read = input.read(buffer, 0, bufferLength);}return messageDigest.digest();} catch (GeneralSecurityException e) {throw Exceptions.unchecked(e);}}public static String string2MD5(String inStr){          MessageDigest md5 = null;          try{              md5 = MessageDigest.getInstance("MD5");          }catch (Exception e){              System.out.println(e.toString());              e.printStackTrace();              return "";          }          char[] charArray = inStr.toCharArray();          byte[] byteArray = new byte[charArray.length];            for (int i = 0; i < charArray.length; i++)              byteArray[i] = (byte) charArray[i];          byte[] md5Bytes = md5.digest(byteArray);          StringBuffer hexValue = new StringBuffer();          for (int i = 0; i < md5Bytes.length; i++){              int val = ((int) md5Bytes[i]) & 0xff;              if (val < 16)                  hexValue.append("0");              hexValue.append(Integer.toHexString(val));          }          return hexValue.toString();        }  }

相关的jar包自行下载