生成6位随机数字其实很简单,只需一行代码,具体如下:
String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
具体实现发送短信验证码功能,以注册为例,其实现代码如下:
这里需要用到第三方短信验证码接口,这里用到的是乐信短信验证码接口,乐信接口API文档说明(http://www.lx598.com/apitext.html),乐信java调用短信验证码接口 demo(http://www.lx598.com/javaCode.html)。
// 注册新用户
@Action(value = "reAimcodeGetVeCode")
public void reAimcodeGetVeCode() {
PrintWriter out;
String result = "验证码申请失败!请重试!";
try {
smsUnit = new SmsUnit(ConfUtil.getProperty("sys_sms_server"));
if (null != account.getACCMOB() && !account.getACCMOB().equals("")) {
account.setACCSTATUS(new BigDecimal(1));//设置使用状态未用
String verifyCode = String
.valueOf(new Random().nextInt(899999) + 100000);//生成短信验证码
account.setFSECURITYCODE(verifyCode);
account.setACCCREATEDATE(new Date()); // 设置验证码失效时间为1分钟
Calendar c = Calendar.getInstance();
c.add(Calendar. Minute in hour, 1);
// 执行短信发送
account.setFREGISTERSOURCE(fromSource);
request.getSession().removeAttribute(ConstValues.WEB_SESSION_PROMOTE);
AccountCriteria ac = new AccountCriteria();
ac.createCriteria().andACCMOBEqualTo(account.getACCMOB());
List<Account> acList = new ArrayList<Account>();
acList = accountService.selectByExample(ac);
if (acList != null && acList.size() > 0) {
String content = "您的验证码为:" + verifyCode+",该码有效期为24小时,该码只能使用一次!【短信签名】";
SendSmsReply sendSmsReply = smsUnit.sendSms(accName,accPwd ,account.getACCMOB(),content,""); //调用第三方接口发送短信 result = sendSmsReply.getReplyMsg() + "&"
+ acList.get(0).getFID() + "&"
+ acList.get(0).getSDKURL();
}
}
} catch (Exception e) {
logger.error("获取验证码失败", e);
} finally {
try {
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
out = response.getWriter();
out.write(result);
} catch (IOException e) {
logger.error("", e);
}
}
} //第三方短信发送接口代码:
/**
* 发送短信
* @param accName 乐信账号用户名
* @param accPwd 乐信账号密码
* @param seed 当前时间 格式:YYYYMMDD HHMISS 例如:20130806102030
* @param aimcodes 手机号多个手机号之间英文半角逗号隔开
* @param content 内容后加签名
* @param schTime 定时时间格式如:2010-01-01 08:00:00
* @return 服务端返回的结果 ok:业务id 或者 错误代码
*/
public static String sendSms(String accName,String accPwd,String mobies,String content,String schTime){
StringBuffer sb = new StringBuffer("http://sdk.lx198.com/sdk/send2?");
try {
String seed=new SimpleDateFormat(dateFormatStr).format(new Date());
sb.append("&accName="+accName);
sb.append("&seed="+seed);
sb.append("&accPwd="+MD5.getMd5String(MD5.getMd5String(accPwd)+seed));
sb.append("&aimcodes="+mobies);
sb.append("&schTime="+URLEncoder.encode(schTime,"UTF-8")); //空格标点符号做encode转换
sb.append("&content="+URLEncoder.encode(content,"UTF-8")); //中文做encode转换
URL url = new URL(sb.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
return in.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}