1. 程式人生 > >【原始碼分享】java如何對接簡訊驗證碼

【原始碼分享】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);
}