【源码分享】java如何对接短信验证码

今天公司提出一个需求,要在现有项目上收集注册用户的真实手机号,由于之前没有接触过这一块,只能寻求度娘的帮助,经过一天的努力,终于完成了,现整理记录下已备查阅。

1 解决方案:在注册时要求用户进行手机验证。
2 寻找短信供应商:由于对这一块不是太懂,大学同学推荐一家他们公司在用的给我。
3 代码实现
首先到互亿无线短信平台注册一个帐号,并登录到用户中心,选验证码模块下载接口文档,文档下载下来是一个压缩包,我们项目是用java的jsp开发的,直接找到目录DEMO/JSP

提示:开始之前先看一下官方对接说明文档

第一步 把前端html代码整合到注册页面
html 代码:

手机 *
验证码  
手机验证码

javascript代码

第一步 把后端jsp代码整合到程序逻辑中。
注意:把code.jsp sms.jsp这两个文件要上传到项目路径下

使用 HttpURLConnection请求短信接口就行了

String postUrl = “http://106.ihuyi.cn/webservice/sms.php?method=Submit”;

int mobile_code = (int)((Math.random()*9+1)*100000); //获取随机数

String account = “用户名”; //查看用户名是登录用户中心->验证码短信->产品总览->APIID
String password = “密码”; //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
String mobile = request.getParameter(“mobile”);
String content = new String(“您的验证码是:” + mobile_code + “。请不要把验证码泄露给其他人。”);
String send_code = request.getParameter(“send_code”);
String session_code = (String)session.getAttribute(“randStr”);

// 此处验证码仅限于纯数字比对
if (Integer.parseInt(send_code) != Integer.valueOf(session_code)) {
String message = new String(“请输入正确的验证码”);
out.println(message);
return;
}

try {

URL url = new URL(postUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);//允许连接提交信息
connection.setRequestMethod("POST");//网页提交方式“GET”、“POST”
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Connection", "Keep-Alive");
StringBuffer sb = new StringBuffer();
sb.append("account="+account);
sb.append("&password="+password);
sb.append("&mobile="+mobile);
sb.append("&content="+content);
OutputStream os = connection.getOutputStream();
os.write(sb.toString().getBytes());
os.close();

String line, result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
while ((line = in.readLine()) != null) {
	result += line + "\n";
}
in.close();
out.println(result);

} catch (IOException e) {
e.printStackTrace(System.out);
}

猜你喜欢

转载自blog.csdn.net/wushi0822/article/details/83141789