往
期
回
顾
1.计算机基础(二)
2.操作系统(一)
3.mysql 索引
4.AJAX
5.COOKIE、session 、token
1
介绍
聚合数据官网:https://www.juhe.cn/login
注册并登录之后,进入首页点击API(需要先实名注册),选择短信API服务,购买完之后会生成一个唯一的key,这个key不要暴露给别人。
参考API文档
接口地址:http://v.juhe.cn/sms/send
返回格式:json/xml
请求方式:http get/post
请求示例:http://v.juhe.cn/sms/send?mobile=手机号码&tpl_id=短信模板ID&tpl_value=%23code%23%3D654654&key=
根据请求示例可以直接在浏览器发送一个短信请求,从示列中我们可以看出需要四个参数,分别是:
手机号mobile
短信模板tpl_id
在下图所示的区域修改添加短信模板,添加完成之后需要审核通过才可以使用
![](https://img6.php1.cn/3cdc5/9921/ae9/a7bc7fdc2a14995a.png)
模板通过之后会生成一个模板id
![](https://img6.php1.cn/3cdc5/9921/ae9/8b8fa1cb18e6b08c.png)
3.tpl_value 变量名和变量值对,如:#code#=431515,整串值需要urlencode,比如正确结果为:%23code%23%3d431515。当然后面的验证码需要我们Java代码生成。
4.生成的key(打马赛克的部分):
![](https://img6.php1.cn/3cdc5/9921/ae9/ba5454952e076949.png)
我们可以直接在浏览器发送:
![](https://img6.php1.cn/3cdc5/9921/ae9/955fc08f384bcfd6.png)
2
Java代码实现
@Controller
@RequestMapping("/sms")
public class SmsController {@Value("${sms.url}")
private String url;@Value("${sms.key}")
private String key;@Value("${sms.tplId}")
private String tplId;@Value("${sms.tplValue}")
private String tplValue;@RequestMapping("/sendVerificationCode")
public ResponseResult sendVerificationCode(String phone, HttpSession session){System.out.println(phone);try {//生成六位随机的验证码Random random &#61; new Random();int randVerificationCode &#61; random.nextInt(999999);//将验证码存放到session中session.setAttribute("randVerificationCode",randVerificationCode);//发送短信Map map&#61;new HashMap<>();map.put("mobile",phone);map.put("key",key);map.put("tpl_id",tplId);map.put("tpl_value",tplValue &#43; randVerificationCode);String doPost &#61; HttpClientUtils.doPost(url, map);System.out.println(doPost);return ResponseResult.success("验证码发送成功");}catch (Exception e) {return ResponseResult.fail("验证码发送失败");}
}
上面四个参数写在属性配置文件中&#xff0c;使用HttpClient发送&#xff0c;前端略。
欢迎识别下方二维码&#xff0c;关注小编微信公众号&#xff0c;可以获取跟多Java资料&#xff1a;
七夕
![](https://img6.php1.cn/3cdc5/9921/ae9/c75a15e28f0865fc.jpeg)