java实现短信验证码发送(架子是springboot 服务平台选择腾讯云短信服务)

业务需求:公司扩展新业务,新增短信验证码提醒服务,负责功能模块完善

暂时只研究了腾讯短信服务的发送(看api谁都能copy出来),短信状态回执(也挺简单,只是自己想复杂了),短信回复回执(暂时没弄明白欢迎大家指点)

2019年8月29日16:56:06

注册一个腾讯云账号(具体就不说了),找到云产品---云通信---短信

进入短信功能页

短信主页,添加应用

点击添加应用,填写信息

添加成功

点击新添加应用,进入应用详情页

记录好自己的sdkappid和appkey(后边代码里主要用这俩)

添加时间回调配置(自己的回调url,如果无需要可以暂时不添加)

这是短信回调的api文档说明可以参考一下,注意url中应该是http而不是https

创建短信签名

我用的是网站,所以是这个

创建短信正文模板,下面会用到

 

具体功能代码实现(先导入pom依赖)<!-- 腾讯短信平台  第一个必须有,其他的看自己缺啥适当添加修改 -->
      

<!-- 腾讯短信平台 第一个必须有,后俩是我缺的,遇到问题看看是不是依赖有问题-->
		<dependency>
			<groupId>com.github.qcloudsms</groupId>
			<artifactId>qcloudsms</artifactId>
			<version>1.0.6</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>
		<!-- 短信发送结束 -->
		<!-- rabbitmq start -->

时间处理util工具类


import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.github.qcloudsms.SmsMobileStatusPuller;
import com.github.qcloudsms.SmsMultiSender;
import com.github.qcloudsms.SmsMultiSenderResult;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.SmsStatusPullCallbackResult;
import com.github.qcloudsms.SmsStatusPullReplyResult;
import com.github.qcloudsms.SmsStatusPuller;
import com.github.qcloudsms.SmsVoicePromptSender;
import com.github.qcloudsms.SmsVoicePromptSenderResult;
import com.github.qcloudsms.SmsVoiceVerifyCodeSender;
import com.github.qcloudsms.SmsVoiceVerifyCodeSenderResult;
import com.github.qcloudsms.TtsVoiceSender;
import com.github.qcloudsms.TtsVoiceSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.github.qcloudsms.httpclient.ProxyHTTPClient;

import cn.com.sinosoft.common.QueueConfig;
import cn.com.sinosoft.util.Msg;

public class SendSMSUtil {
	// 短信应用 SDK AppID
	public final static int appid = 1400248104; // SDK AppID 以1400开头
	// 短信应用 SDK AppKey
	public final static String appkey = "key的话大家就自己申请吧";
	// 需要发送短信的手机号码
	final static String[] phoneNumbers = { "21212313123", "12345678902", "12345678903" };
	// 短信模板 ID,需要在短信应用中申请
	final static int templateId = 404720; // NOTE: 这里的模板 ID`7839`只是示例,真实的模板 ID 需要在短信控制台中申请
	// 签名
	final static String smsSign = "学习分享"; // NOTE: 签名参数使用的是`签名内容`,而不是`签名ID`。这里的签名只是示例,真实的签名需要在短信控制台申请

	// 单条消息发送,,必须必须和配置的模板消息内容相同,否则发送失败
	public void sendSingleSMS(String countries, String phone, String Message) {
		try {
			SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
			SmsSingleSenderResult result = ssender.send(0, countries, phone,
					Message + "为您的登录验证码,请于1分钟内填写。如非本人操作,请忽略本短信。 ", "", "");
			JSONObject obj = new JSONObject(result.toString());
			int res = (int) obj.get("result");
			if (res == 0) {
				System.out.println("成功");
			} else {
				System.out.println(res);
				String errmsg = (String) obj.get("errmsg");
				System.out.println(errmsg);
			}
		} catch (HTTPException e) {
			// HTTP 响应码错误
			e.printStackTrace();
		} catch (JSONException e) {
			// JSON 解析错误
			e.printStackTrace();
		} catch (IOException e) {
			// 网络 IO 错误
			e.printStackTrace();
		}
	}

	// 2群发消息,必须必须和配置的模板消息内容相同,否则发送失败
	public void sendGroupSMS(String countrie, String[] phones, String Message) {
		try {
			SmsMultiSender msender = new SmsMultiSender(appid, appkey);
			SmsMultiSenderResult result = msender.send(0, countrie, phones, "为您的登录验证码,请于1分钟内填写。如非本人操作,请忽略本短信。 ", "",
					"");
			JSONObject obj = new JSONObject(result.toString());
			int res = (int) obj.get("result");
			if (res == 0) {
				System.out.println("成功");
			} else {
				System.out.println(res);
				String errmsg = (String) obj.get("errmsg");
				System.out.println(errmsg);
			}
			// System.out.println(result);
		} catch (HTTPException e) {
			// HTTP 响应码错误
			e.printStackTrace();
		} catch (JSONException e) {
			// JSON 解析错误
			e.printStackTrace();
		} catch (IOException e) {
			// 网络 IO 错误
			e.printStackTrace();
		}
	}

	// 3指定模板id单发消息
	public Msg sendTemplateSingleSMS(String countrie, String phones, String code) {
		Msg msg = new Msg();
		try {
			String[] params = { code, "1" };
			SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
			SmsSingleSenderResult result = ssender.sendWithParam(countrie, phones, templateId, params, smsSign, "", "");
			JSONObject obj = new JSONObject(result.toString());
			int res = (int) obj.get("result");
			msg.setResult(res);

			if (res == 0) {
				System.out.println("成功");
			} else {
				System.out.println(res);
				String errmsg = (String) obj.get("errmsg");
				msg.setMessage(errmsg);
				System.out.println(errmsg);
			}
			System.out.println(result);
		} catch (HTTPException e) {
			// HTTP 响应码错误
			e.printStackTrace();
		} catch (JSONException e) {
			// JSON 解析错误
			e.printStackTrace();
		} catch (IOException e) {
			// 网络 IO 错误
			e.printStackTrace();
		}
		return msg;
	}

	// 4指定模板id群发消息
	public void sendTemplatesGroupSMS(String countrie, String[] phones, String code) {
		try {
			String[] params = { code };
			SmsMultiSender msender = new SmsMultiSender(appid, appkey);
			SmsMultiSenderResult result = msender.sendWithParam(countrie, phones, templateId, params, smsSign, "", "");
			JSONObject obj = new JSONObject(result.toString());
			int res = (int) obj.get("result");
			if (res == 0) {
				System.out.println("成功");
			} else {
				System.out.println(res);
				String errmsg = (String) obj.get("errmsg");
				System.out.println(errmsg);
			}
			System.out.println(result);
		} catch (HTTPException e) {
			// HTTP 响应码错误
			e.printStackTrace();
		} catch (JSONException e) {
			// JSON 解析错误
			e.printStackTrace();
		} catch (IOException e) {
			// 网络 IO 错误
			e.printStackTrace();
		}
	}

	// 5拉取消息回执,,,有我自己的业务逻辑处理,大家可以自己修改
	public static List<SMSEntity> getSMSReceipt(int maxNum) {
		try {
			// Note: 短信拉取功能需要联系腾讯云短信技术支持(QQ:3012203387)开通权限
			maxNum = 10; // 单次拉取最大量
			SmsStatusPuller spuller = new SmsStatusPuller(appid, appkey);

			// 拉取短信回执
			SmsStatusPullCallbackResult callbackResult = spuller.pullCallback(maxNum);
			System.out.println(callbackResult);

			// 拉取回复,国际/港澳台短信不支持回复功能
			// SmsStatusPullReplyResult replyResult = spuller.pullReply(maxNum);
			// System.out.println(replyResult);
			JSONObject obj = new JSONObject(callbackResult.toString());
			int res = (int) obj.get("result");
			List<SMSEntity> list = new ArrayList<SMSEntity>();
			if (res == 0) {
            /**
               *        这部分是我自己的业务逻辑处理,大家可以自己修改
               *
               */
				System.out.println("成功");
				System.out.println("data:" + obj.get("data"));
				
				String str = obj.get("data").toString();
				if (str != "[]" && !(str.equals("[]"))) {
					String[] arr = str.split("},");
					if (arr.length > 0) {
						for (int i = 0; i < arr.length; i++) {
							String a = arr[i].replace("[", "").replace("]", "").toString() + "}";
							System.out.println(a);
							JSONObject objs = new JSONObject(a);
							String user_receive_time = (String) objs.get("user_receive_time");
							//String pull_type = (String) objs.get("pull_type");
							String mobile = (String) objs.get("mobile");
							String report_status = (String) objs.get("report_status");
							String errmsg = (String) objs.get("errmsg");
							String description = (String) objs.get("description");
							String nationcode = (String) objs.get("nationcode");
							String sid = (String) objs.get("sid");
							SMSEntity sms = new SMSEntity(sid,user_receive_time,mobile,nationcode,report_status,errmsg,description);
							list.add(sms);
						}
					}

				}
				return list;
			} else {
				System.out.println(res);
				String errmsg = (String) obj.get("errmsg");
				System.out.println(errmsg);
			}
		} catch (HTTPException e) {
			// HTTP 响应码错误
			e.printStackTrace();
		} catch (JSONException e) {
			// JSON 解析错误
			e.printStackTrace();
		} catch (IOException e) {
			// 网络 IO 错误
			e.printStackTrace();
		}
		return null;
	}

	// 6拉取单个短信状态
	public static void getSingleReceipt(String countrie, String phones, Long l, Long m, int maxNum) {
		try {
			// l = 1511125600; // 开始时间(UNIX timestamp)
			// m = 1511841600; // 结束时间(UNIX timestamp)
			maxNum = 10; // 单次拉取最大量
			SmsMobileStatusPuller mspuller = new SmsMobileStatusPuller(appid, appkey);

			// 拉取短信回执
			SmsStatusPullCallbackResult callbackResult = mspuller.pullCallback(countrie, phones, l, m, maxNum);
			System.out.println(callbackResult);

			// 拉取回复,国际/港澳台短信不支持回复功能
			SmsStatusPullReplyResult replyResult = mspuller.pullReply("86", phones, l, m, maxNum);
			System.out.println(replyResult);
		} catch (HTTPException e) {
			// HTTP 响应码错误
			e.printStackTrace();
		} catch (JSONException e) {
			// JSON 解析错误
			e.printStackTrace();
		} catch (IOException e) {
			// 网络 IO 错误
			e.printStackTrace();
		}
	}

	// 7语音验证码,,,要花钱,针对企业用户
	public void sendVoiceVerificationCode(String countrie, String phones, String code) {
		try {
			SmsVoiceVerifyCodeSender vvcsender = new SmsVoiceVerifyCodeSender(appid, appkey);
			SmsVoiceVerifyCodeSenderResult result = vvcsender.send(countrie, phones, code, 2, "");
			System.out.println(result);
		} catch (HTTPException e) {
			// HTTP 响应码错误
			e.printStackTrace();
		} catch (JSONException e) {
			// JSON 解析错误
			e.printStackTrace();
		} catch (IOException e) {
			// 网络 IO 错误
			e.printStackTrace();
		}
	}

	// 8发送语音通知,,花钱,针对企业用户
	public void sendVoiceMessage(String countrie, String phones, String code) {
		try {
			SmsVoicePromptSender vpsender = new SmsVoicePromptSender(appid, appkey);
			SmsVoicePromptSenderResult result = vpsender.send(countrie, phones, 2, 2, code, "");
			System.out.println(result);
		} catch (HTTPException e) {
			// HTTP 响应码错误
			e.printStackTrace();
		} catch (JSONException e) {
			// JSON 解析错误
			e.printStackTrace();
		} catch (IOException e) {
			// 网络 IO 错误
			e.printStackTrace();
		}
	}

	// 9指定模板语音通知,,同上
	public void sendTemplateVoiceMessage(String countrie, String phones, String code) {
		try {
			int templateId = 45221;
			String[] params = { code };
			TtsVoiceSender tvsender = new TtsVoiceSender(appid, appkey);
			TtsVoiceSenderResult result = tvsender.send(countrie, phones, templateId, params, 2, "");
			System.out.println(result);
		} catch (HTTPException e) {
			// HTTP 响应码错误
			e.printStackTrace();
		} catch (JSONException e) {
			// JSON 解析错误
			e.printStackTrace();
		} catch (IOException e) {
			// 网络 IO 错误
			e.printStackTrace();
		}
	}

	/// 部分环境需要使用代理才能上网,可使用 ProxyHTTPClient 来发送请求,示例如下:

	public void createProxyHTTPClient() {
		try {
			// 创建一个代理 httpclient
			ProxyHTTPClient httpclient = new ProxyHTTPClient("127.0.0.1", 8080, "http");

			String[] params = { "5678" };
			SmsSingleSender ssender = new SmsSingleSender(appid, appkey, httpclient);
			SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumbers[0], templateId, params, smsSign, "",
					""); // 签名参数未提供或者为空时,会使用默认签名发送短信
			System.out.println(result);
		} catch (HTTPException e) {
			// HTTP 响应码错误
			e.printStackTrace();
		} catch (JSONException e) {
			// JSON 解析错误
			e.printStackTrace();
		} catch (IOException e) {
			// 网络 IO 错误
			e.printStackTrace();
		}
	}
	// 多个线程可以共用一个连接池发送 API 请求,多线程并发单发短信示例如下:
}

上边是腾讯api中说明的内容,我自己加了些自己的业务逻辑,均已标注,有用不到的可以删除


public class RandomUtil {
	//生成指定位数字符串
	public static String createRandomInt(int num ) {
		int a=(int) Math.pow(10,num);
		int result = new Random().nextInt(a);
		String code = String.format("%"+num+"d", result);
		return code;
		
	}
	//生成指定位混合符串
	public static String createRandomString(int num ) {
		String string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//保存数字0-9 和 大小写字母
		StringBuffer sb = new StringBuffer(); //声明一个StringBuffer对象sb 保存 验证码
		for (int i = 0; i < num; i++) {
			Random random = new Random();//创建一个新的随机数生成器
			int index = random.nextInt(string.length());//返回[0,string.length)范围的int值    作用:保存下标
			char ch = string.charAt(index);//charAt() : 返回指定索引处的 char 值   ==》赋值给char字符对象ch
			sb.append(ch);// append(char c) :将 char 参数的字符串表示形式追加到此序列  ==》即将每次获取的ch值作拼接
		}
		return sb.toString();//toString() : 返回此序列中数据的字符串表示形式   ==》即返回一个String类型的数据
	}
}

随机生成验证码的工具类,忘了从哪里看到的了,如果作者看到可以联系我


public class AreaNumber {
	public final static String[] AreaNumber = { "1", "1-264", "1-268", "1-242", "1-246", "1-441", "1-284", "1-345", "1-767",
			"1-809", "1-473", "1-876", "1-664", "1-787", "1-869", "1-758", "1-784", "1-868", "1-649", "1-340", "1-671",
			"1-670", "20", "210", "211", "212", "213", "214", "215", "216", "217", "218", "219", "220", "221", "222",
			"223", "224", "225", "226", "227", "228", "229", "230", "231", "232", "233", "234", "235", "236", "237",
			"238", "239", "240", "241", "242", "243", "244", "245", "246", "247", "248", "249", "250", "251", "252",
			"253", "254", "255", "256", "257", "258", "259", "260", "261", "262", "263", "264", "265", "266", "267",
			"268", "269", "27", "290", "291", "297", "298", "299", "30", "31", "32", "33", "34", "350", "351", "352",
			"353", "354", "355", "356", "357", "358", "359", "36", "37", "370", "371", "372", "373", "374", "375",
			"376", "377", "378", "379", "38", "380", "381", "382", "383", "384", "385", "386", "387", "388", "389",
			"39", "40", "41", "42", "420", "421", "422", "423", "424", "425", "426", "427", "428", "429", "43", "44",
			"45", "46", "47", "48", "49", "500", "501", "502", "503", "504", "505", "506", "507", "508", "509", "51",
			"52", "53", "54", "55", "56", "57", "58", "590", "591", "592", "593", "594", "595", "596", "597", "598",
			"599", "599-9", "60", "61", "62", "63", "64", "65", "66", "670", "672", "673", "674", "675", "676", "677",
			"678", "679", "680", "681", "682", "683", "684", "685", "686", "687", "688", "689", "690", "691", "692",
			"693", "694", "695", "696", "697", "698", "699", "7 ", "800", "808", "81", "82", "83", "84", "850", "851",
			"852", "853", "854", "855", "856", "857", "858", "859", "86", "870", "871", "872", "873", "874", "875",
			"876", "877", "878", "879", "880", "881", "882", "883", "884", "885", "886", "90", "91", "92", "93", "94",
			"95", "960", "961", "962", "963", "964", "965", "966", "967", "968", "969", "970", "971", "972", "973",
			"974", "975", "976", "977", "979", "98", "990", "991", "992", "993", "994", "995", "996", "998" };
}

手机号的区号,自己找的弄得,可能不全


public class SMSEntity {

	private String sid;
	private String user_receive_time;
	private String mobile;
	private String nationcode;
	private String report_status;
	private String errmsg;
	private String description;
	
	public String getUser_receive_time() {
		return user_receive_time;
	}
	public void setUser_receive_time(String user_receive_time) {
		this.user_receive_time = user_receive_time;
	}
	
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getReport_status() {
		return report_status;
	}
	public void setReport_status(String report_status) {
		this.report_status = report_status;
	}
	public String getErrmsg() {
		return errmsg;
	}
	public void setErrmsg(String errmsg) {
		this.errmsg = errmsg;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	
	public String getSid() {
		return sid;
	}
	public void setSid(String sid) {
		this.sid = sid;
	}
	public String getNationcode() {
		return nationcode;
	}
	public void setNationcode(String nationcode) {
		this.nationcode = nationcode;
	}
	public SMSEntity() {
		super();
	}
	public SMSEntity(String sid, String user_receive_time, String mobile, String nationcode, String report_status,
			String errmsg, String description) {
		super();
		this.sid = sid;
		this.user_receive_time = user_receive_time;
		this.mobile = mobile;
		this.nationcode = nationcode;
		this.report_status = report_status;
		this.errmsg = errmsg;
		this.description = description;
	}
	
	
	
}

短信实体类,自己写的,可以直接拿去用,也可以改


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

//获取http请求中json
public class ParameterUtil {
    public static JSONObject getParameters(HttpServletRequest request)
            throws UnsupportedEncodingException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (ServletInputStream) request.getInputStream(), "utf-8"));
        StringBuffer sb = new StringBuffer("");
        String temp;
        while ((temp = br.readLine()) != null) {
            sb.append(temp);
        }
        br.close();
        String acceptjson = sb.toString();
        JSONObject jo = null;
        if (acceptjson != "") {
            jo = JSONObject.fromObject(acceptjson);
        }
        return jo;
    }
}
///*********///

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
//shiro加密哈希散列
public class HashSatlUtil {
	public static Map<String, Object> HashSaltUtil(String method,String pass,int times){
		Map<String, Object> map = new HashMap<>();
		String salt = new SecureRandomNumberGenerator().nextBytes().toString();
		String encodedPassword = new SimpleHash(method, pass, salt, times).toString();
		map.put("salt", salt);
		map.put("encodedPassword", encodedPassword);
		return map;
	}
}




import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
    /**
     * 检查字符串是否为null或者空
     *
     * */
    public static boolean isNotNullOrEmpty(final String str) {
        return null != str && !"".equals(str) && !"null".equals(str);
    }
    /**
     * 检查字符串是否为null或者空
     *
     * */
    public static boolean isNullOrEmpty(final String str) {
        return !isNotNullOrEmpty(str);
    }

    /**
     * 将字符串以逗号分割成为list
     * @param string
     * @return
     */
    public static List<String> arrayToList(String string){
        String[] array = string.split(",");
        List<String> paramList =java.util.Arrays.asList(array);
        return paramList;
    }


    /**
     * 检测手机号是否符合格式
     *
     * */
    public static boolean checkPhone(String phoneNumber) {
        Pattern pattern = Pattern.compile("^1[3|4|5|7|8][0-9]{9}$");
        Matcher matcher = pattern.matcher(phoneNumber);
        return matcher.matches();
    }


    /**
     * 检测email是否符合格式
     *
     * */
    public static boolean checkEmail(String email) {
        Pattern pattern = Pattern.compile("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+");
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
}

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DataUtil {
	private static Logger logger = LoggerFactory.getLogger(DataUtil.class);
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	//
	private static SimpleDateFormat sdfFile = new SimpleDateFormat("yyyyMMddhhmmss");
	//
	private static SimpleDateFormat sdf_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	
	//字符串转日期,年月日时分秒
	public static Date getDateHMS(String str)throws Exception{
		return sdf_time.parse(str);
	}
	//字符串转成日期,年月日
	public static Date getDate(String dateStr) throws Exception{
		return sdf.parse(dateStr);
	}
	
	//字符串转成日期
	public static String getStringDate(Date date) throws Exception{
		return sdf.format(date);
	}
	
	//字符串转成日期
	public static String getStringDateTime(Date date) throws Exception{
		return sdfFile.format(date);
	}
	
	//字符串转成日期
	public static String DateTimeToString(Date date) throws Exception{
		return sdf_time.format(date);
	}
	
	//字符串转成日期
	public static Timestamp getChangeDateTime(String date) throws Exception{
		Timestamp ts = new Timestamp(System.currentTimeMillis());
		ts = Timestamp.valueOf(date);
		return ts;
	}
	
	//字符串转成日期
	public static Timestamp getDateTime() throws Exception{
		Date date = new Date();
		Timestamp ts = new Timestamp(System.currentTimeMillis());
		String date1 = sdf_time.format(date);
		ts = Timestamp.valueOf(date1);
		return ts;
	}
	
	//字符串转成详细日期
	public static Timestamp getStringDateTime(String date) throws Exception{
		Timestamp ts = new Timestamp(System.currentTimeMillis());
		ts = Timestamp.valueOf(date);
		return ts;
	}
	
	public static Date getNewEndTime(double hours) throws Exception{
		Date date = new Date();
	    date.setTime(date.getTime() + Math.round(hours*60*60*1000));
	    return date;
	} 
	
	//比较两个时间的大小
	public static boolean getTimeResult(Date start,Date end) throws Exception{
		long sts = 	start.getTime();
		long ste = end.getTime();
		logger.info("比较时间大小:");
		if(sts>ste) {
			//前边大于后边
			logger.info("前大于后:");
			return true;
		}else {
			logger.info("前小于后");
			return false;
		}
		
	}
//几天前时间
	public static Date getDateBefore(Date d, int day) {
	    Calendar now = Calendar.getInstance();
	    now.setTime(d);
	    now.set(Calendar.DATE, now.get(Calendar.DATE) - day);//+后 -前
	    return now.getTime();
	}
/**
 * 得到几天后的时间
 *
 * @param d
 * @param day
 * @return
 */
public static Date getDateAfter(Date d, int day) {
    Calendar now = Calendar.getInstance();
    now.setTime(d);
    now.set(Calendar.DATE, now.get(Calendar.DATE) + day);//+后 -前
    return now.getTime();
}
public static String getDateAfterString(Date d, int day) {
    Calendar now = Calendar.getInstance();
    now.setTime(d);
    now.set(Calendar.DATE, now.get(Calendar.DATE) + day);//+后 -前
    Date date =now.getTime();
    return sdf_time.format(date);
}
/**
 * 得到几分钟后时间
 */
 public static String getDateAfterStringByMINUTE(Date d, int day) {
	    Calendar now = Calendar.getInstance();
	    now.setTime(d);
	    now.set(Calendar.MINUTE, now.get(Calendar.MINUTE) + day);//+后 -前
	    Date date =now.getTime();
	    return sdf_time.format(date);
	}
 //当前时间转unix时间戳类型
 public static Long timeChangeTimestamp(Date date) {
	 
	  //普通时间 转换 Unix timestamp  
    // DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
     long epoch = date.getTime()/1000;               //  获得 unix timestamp
     System.out.println("2016-3-1 unix stamp is "+ epoch);   
     return epoch; 
      
 }  
 //unix timestamp转data
 public static Date TimestampChangeData(Long date) {
	// unix timestamp 转换 普通时间
     Date d2  = new Date(date * 1000);
     return d2;
 }
	
}

几个基础的base工具了
// 普通方式发送短信消息
	@ResponseBody
	@RequestMapping("/sendMessage")
	public Msg sendMessage(String address, String mobile, HttpSession session) {
		logger.info("短信模板消息发送");
		Msg msg = new Msg();
		try {
			String result = RandomUtil.createRandomInt(6);
			address = address.replace("+", "");// 替换前端传过来的
			String message = address + mobile + result;
			// 验证码过期时间
			String unEffectiveTime = DataUtil.getDateAfterStringByMINUTE(new Date(), 1);
			session.setAttribute("unEffectiveTime", unEffectiveTime);
			session.setAttribute("VerificationCode", result);
            //方法一,直接调用
            SendSMSUtil ssu = new SendSMSUtil();
		    ssu.sendTemplateSingleSMS(address, mobile,result);
			/**
			 * 方法二:将短信消息内容放到队列中发送
			 */
			String msgId = UUID.randomUUID().toString();
			CorrelationData correlationData = new CorrelationData(msgId);
			rabbitTemplate.convertAndSend("first_exchange", "queue_one_key1", message, correlationData);
			msg.setResult(0);
			msg.setMessage("验证码发送成功");
		} catch (Exception e) {
			logger.error("发送验证码异常err:{}", e.getMessage());
			msg.setResult(1);
			msg.setMessage("验证码发送失败请重试");
		}
		return msg;
	}
	@ResponseBody
	@RequestMapping("/send")
	public String send() {
		SendSMSUtil ssu = new SendSMSUtil();
		ssu.sendTemplateSingleSMS("86", "self mobile","123456");
		return null;
	}
	//手动拉取消息回执+入库
	@ResponseBody
	@RequestMapping("/smsSendResult")
	public void smsSendResult(String strs) {
		
		
		 List<SMSEntity> list= SendSMSUtil.getSMSReceipt(1);
		 if(list!=null && list.size()>0) {
			 //数据入库
			 try {
				int result = jyxtUserService.smsSendResult(list);
			} catch (Exception e) {
				logger.error("短信回执异常:{}",e.getMessage());
				e.printStackTrace();
			}
		 }
		
	}
	//查询指定号码在指定时间范围内发送的短信
	@ResponseBody
	@RequestMapping("/getSingleReceipt")
	public void getSingleReceipt() {
		SendSMSUtil.getSingleReceipt("86", "self mobile",  DataUtil.timeChangeTimestamp(DataUtil.getDateBefore(new Date(), 3)),  DataUtil.timeChangeTimestamp(new Date()), 10);
		
	}
	//回调方法获取参数+入库
	@ResponseBody
	@RequestMapping("/smsSendRedirect")
	public void smsSendRedirect(HttpServletRequest request ,HttpServletResponse response) {
		net.sf.json.JSONObject parameters;
		try {
			parameters = ParameterUtil.getParameters(request);
			String user_receive_time = (String) parameters.get("user_receive_time");
			String nationcode = (String) parameters.get("nationcode");
			String mobile = (String) parameters.get("mobile");
			String report_status = (String) parameters.get("report_status");
			String errmsg = (String) parameters.get("errmsg");
			String description = (String) parameters.get("description");
			String sid = (String) parameters.get("sid");
			//入库
			SMSEntity sms = new SMSEntity( sid,  user_receive_time,  mobile,  nationcode,  report_status,
					 errmsg,  description) ;
			 List<SMSEntity> list= new ArrayList<SMSEntity>();
			 list.add(sms);
			 if(list!=null && list.size()>0) {
				 //数据入库
				 try {
					int result = jyxtUserService.smsSendResult(list);
					
				} catch (Exception e) {
					logger.error("短信回执异常:{}",e.getMessage());
					e.printStackTrace();
				}
			 }
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        
		
	}

最后这个是controller里边的调用方法,可以拿去试试

以上是博主自己的总结,有不足之处欢迎大家提出指正

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值