脚本宝典收集整理的这篇文章主要介绍了java发送短信验证码,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
1.选择一个短信平台,因为之前项目用的是赛邮云通信(submail),所以在这里以此为例。
2.需要到平台上创建账号,先参阅api文档研究入参。
(1)需要用到应用Id和密钥进行身份鉴权,在应用集成-》应用页面进行创建
(2)创建短信模板,短信-》新建 页面可以创建新的短信模板
3.接口调用
用到的jar包:commons-LOGging.jar gson.jar httpclient.jar httpcore.jar json-simple.jar
HttpPost httpPost = new HttpPost();
CloseableHttpClient client = HttpClientBuilder.create().build(); httpPost.setURI(new URI("https://api.submail.cn/message/xsend.json")); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("appid", "*****")); //(1)中创建的appid params.add(new BasicNameValuePair("to", "***********")); //发送的手机号 params.add(new BasicNameValuePair("project", "****")); //(2)中创建的短信模板标识 params.add(new BasicNameValuePair("signature", "*****************")); //(1)中创建的密钥 Map<String,String> vars = new HashMap<>(); vars.put("code","5555"); params.add(new BasicNameValuePair("vars", JSONObject.toJSONString(vars))); //模板中可设可变参数,这里为传参。 在模板中的设置为@var(code) httpPost.setEntity(new UrlEncodeDFormEntity(params,"utf-8")); HttpResponse response = client.execute(httpPost); String s = EntityUtils.toString(response.getEntity()); System.out.println(s);
4.一般短信验证码会有时间限制,即几分钟内有效。这里用到的是redis来存取验证码及控制时间。
话不多说,上源码!
@Resource private RedisTemplate redisTemplate; BoundValueoperations valueOps = redisTemplate.boundValueOps(phone); @H_337_126@String code = (String) valueOps.get(); //发送短信间隔时间1分钟,验证码有效时间2分钟 int timeout = 1; int expireMinute = 2; int codeLength = 6; if (StringUtils.isNotEmpty(code)) { Long expire = valueOps.getExpire(); if (expire >= (expireMinute - timeout) * 60) { throw new ServiceException(StatusCode.ERROR_COMMON, "发送验证码间隔不能小于" + timeout + "分钟"); } else { code = RandomStringUtils.getRandomNumberStr(codeLength); //此方法为创建一个随机六位数,即验证码。 valueOps.set(code); valueOps.expire(expireMinute, TimeUnit.MINUTES); } } else { code = RandomStringUtils.getRandomNumberStr(codeLength); valueOps.set(code); valueOps.expire(expireMinute, TimeUnit.MINUTES); }
OK,到这里就搞定了!
以上是脚本宝典为你收集整理的java发送短信验证码全部内容,希望文章能够帮你解决java发送短信验证码所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。