Java程式設計師從笨鳥到菜鳥(五十六) java 實現簡訊驗證碼
阿新 • • 發佈:2018-12-14
方式一:
1、註冊
2、檢視 API 介面
3、獲取簡訊金鑰
4、工具類:
SendMsgUtil.java
程式碼
package util; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import java.util.HashMap; /** * create by
[email protected] on 2018/10/9 09:04 * 傳送驗證碼的工具類 **/ public class SendMsgUtil { public static HashMap<String,String> getMessageStatus(String phone) throws Exception { HashMap<String,String> hashMap = new HashMap<>(); // 連線第三方平臺 PostMethod postMethod = new PostMethod("http://utf8.api.smschinese.cn/"); postMethod.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); // 在標頭檔案中設定轉碼 // 生成隨機字元的驗證碼 String randNum = String.valueOf(RandomUtil.getRandNum()); // 簡訊模板 NameValuePair[] data = { new NameValuePair("Uid", "****"), // sms 簡訊通 註冊的使用者名稱 new NameValuePair("key", "*************"), // 金鑰 new NameValuePair("smsMob", phone), // 要傳送的目標手機號 new NameValuePair("smsText", "驗證碼:" + randNum + ",傳送") // 自定義傳送內容 }; for (NameValuePair n: data ) { // 列印資訊方便除錯 System.out.println("簡訊模板為:" + n); } postMethod.setRequestBody(data); HttpClient client = new HttpClient(); client.executeMethod(postMethod); // 獲取 http 頭 Header[] headers = postMethod.getRequestHeaders(); int statusCode = postMethod.getStatusCode(); System.out.println("statusCode:" + statusCode); for (Header h: headers) { // 列印資訊方便除錯 System.out.println(h.toString()); } // 獲取返回訊息 String result = new String(postMethod.getResponseBodyAsString().getBytes("utf-8")); System.out.println(result); // 將返回訊息和 6 位數驗證碼放入 map 裡面 hashMap.put("result",result); hashMap.put("code",randNum); // 斷開第三方平臺連線 postMethod.releaseConnection(); return hashMap; } }
獲取隨機 6 位數的驗證碼:
RandomUtil.java
程式碼:
package util;
/**
* create by [email protected] on 2018/10/9 09:02
* 隨機生成驗證碼工具類
**/
public class RandomUtil {
// 得到隨機六位數
public static int getRandNum() {
return (int)((Math.random()*9+1)*100000);
}
}
控制層實現:
MessageController.java
程式碼:
package controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import entity.Phone;
import org.apache.commons.httpclient.HttpException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import service.MessageService;
import util.SendMsgUtil;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
/**
* create by [email protected] on 2018/10/9 09:32
* 傳送簡訊校驗碼控制層實現
*
**/
@Controller
@RequestMapping("/message")
public class MessageController {
/**
* 傳送校驗碼
* @param phone 目標手機號
* */
@RequestMapping(value = "/send", method = RequestMethod.GET)
@ResponseBody
public String send(String phone, HttpServletRequest request) throws HttpException, Exception {
HashMap<String, String> map = SendMsgUtil.getMessageStatus(phone);
HashMap<String, String> hashMap = new HashMap<>(); // 用於存放返回結果
ObjectMapper objectMapper = new ObjectMapper();
String result = map.get("result");
HttpSession session = request.getSession(); // 設定 session
session.setMaxInactiveInterval(60 * 1); // 快取設定 1 分鐘內有效
if (result.trim().equals("1")) { // 標誌位 1:成功
String code = map.get("code");
System.out.println("驗證碼為:" + code);
session.setAttribute("code",code); // 將收到的驗證碼放入 session 中
hashMap.put("result","success");
} else { // 標誌位 0:失敗
hashMap.put("result","fail");
}
return objectMapper.writeValueAsString(hashMap);
}
/**
* 比對校驗碼
* */
@RequestMapping(value = "/checkCode", method = RequestMethod.POST)
@ResponseBody
public String checkCode(String code, Phone phone, HttpServletRequest request) throws Exception{
HashMap<String, String> map = new HashMap<>();
ObjectMapper objectMapper = new ObjectMapper(); // json 轉換函式
HttpSession session = request.getSession(); // 設定 session
String sessionCode = (String)session.getAttribute("code");
if ((code).equals(sessionCode)) { // 和快取比對驗證碼是否相同
map.put("result", "success");
} else {
map.put("result", "fail");
}
return objectMapper.writeValueAsString(map);
}
}
方式二:
1、註冊
2、檢視 API
3、下載 DEMO
4、工具類:
Config.java
程式碼:
package util;
/**
* create by [email protected] on 2018/10/9 13:14
* 使用秒嘀簡訊傳送驗證碼
* 配置檔案
**/
public class Config {
/**
* url 前半部分
* */
public static final String BASE_URL = "https://api.miaodiyun.com/20150822";
/**
* 開發者註冊後系統自動生成的賬號
*/
public static final String ACCOUNT_SID = "****************";
/**
* 開發者註冊後系統自動生成的TOKEN
*/
public static final String AUTH_TOKEN = "*************";
/**
* 響應資料型別, JSON或XML
*/
public static final String RESP_DATA_TYPE = "json";
}
HttpUtil.java
程式碼:
package util;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* create by [email protected] on 2018/10/9 13:24
* 秒嘀科技簡訊驗證碼
* http 請求工具類
**/
public class HttpUtil {
/**
* 構造通用引數timestamp、sig和respDataType
*
* @return
*/
public static String createCommonParam() {
// 時間戳
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String timestamp = sdf.format(new Date());
// 簽名
String sig = DigestUtils.md5Hex(Config.ACCOUNT_SID + Config.AUTH_TOKEN + timestamp);
return "×tamp=" + timestamp + "&sig=" + sig + "&respDataType=" + Config.RESP_DATA_TYPE;
}
/**
* post請求
*
* @param url
* 功能和操作
* @param body
* 要post的資料
* @return
* @throws IOException
*/
public static String post(String url, String body) throws IOException {
System.out.println("url:" + System.lineSeparator() + url);
System.out.println("body:" + System.lineSeparator() + body);
String result = "";
try
{
OutputStreamWriter out = null;
BufferedReader in = null;
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
// 設定連線引數
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(20000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 提交資料
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(body);
out.flush();
// 讀取返回資料
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = "";
boolean firstLine = true; // 讀第一行不加換行符
while ((line = in.readLine()) != null)
{
if (firstLine)
{
firstLine = false;
} else
{
result += System.lineSeparator();
}
result += line;
}
} catch (Exception e)
{
e.printStackTrace();
}
return result;
}
/**
* 回撥測試工具方法
*
* @param url
* @param body
* @return
*/
public static String postHuiDiao(String url, String body)
{
String result = "";
try
{
OutputStreamWriter out = null;
BufferedReader in = null;
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
// 設定連線引數
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(20000);
// 提交資料
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(body);
out.flush();
// 讀取返回資料
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = "";
boolean firstLine = true; // 讀第一行不加換行符
while ((line = in.readLine()) != null)
{
if (firstLine)
{
firstLine = false;
} else
{
result += System.lineSeparator();
}
result += line;
}
} catch (Exception e)
{
e.printStackTrace();
}
return result;
}
}
IndustrySMS.java
程式碼
package util;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
/**
* create by [email protected] on 2018/10/9 13:32
* 秒嘀科技簡訊驗證碼
* 驗證碼通知簡訊介面
**/
public class IndustrySMS {
private static String operation = "/industrySMS/sendSMS";
private static String accountSid = Config.ACCOUNT_SID;
private static String to = "";
private static String param = "";
private static String smsContent = "【易科技】尊敬的使用者,您好,登入驗證碼:";
/**
* 驗證碼通知簡訊
*/
public static void execute() throws IOException {
HashMap<String, String> map = new HashMap<>();
// 生成驗證碼
param = String.valueOf(RandomUtil.getRandNum());
String tmpSmsContent = null;
try {
tmpSmsContent = URLEncoder.encode(smsContent + param + ",如非本人操作,請忽略此簡訊。", "UTF-8"); // 注意模板中的逗號是中文的
System.out.println(smsContent + param + ", 如非本人操作,請忽略此簡訊。");
} catch (Exception e){
}
System.out.println("生成驗證碼為:" + param);
String url = Config.BASE_URL + operation;
String body = "accountSid=" + accountSid + "&to=" + to + "&smsContent=" + tmpSmsContent
+ HttpUtil.createCommonParam();
// 提交請求
String result = HttpUtil.post(url, body);
System.out.println("result:" + System.lineSeparator() + result);
String status = result.substring(12,18);
System.out.println("status:" + status);
}
public static HashMap<String, String> executeHash(String phone) throws Exception {
HashMap<String, String> map = new HashMap<>();
// 生成驗證碼
param = String.valueOf(RandomUtil.getRandNum());
String tmpSmsContent = null;
try {
tmpSmsContent = URLEncoder.encode(smsContent + param + ",如非本人操作,請忽略此簡訊。", "UTF-8"); // 注意模板中的逗號是中文的
System.out.println(smsContent + param + ", 如非本人操作,請忽略此簡訊。");
} catch (Exception e){
}
String url = Config.BASE_URL + operation;
String body = "accountSid=" + accountSid + "&to=" + phone + "&smsContent=" + tmpSmsContent
+ HttpUtil.createCommonParam();
// 提交請求
String result = HttpUtil.post(url, body);
System.out.println("result:" + System.lineSeparator() + result);
String status = result.substring(13,18);
map.put("respCode", status);
map.put("checkCode",param);
return map;
}
}
控制層程式碼實現;
MiaoDiController.java
程式碼:
package controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import util.IndustrySMS;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
/**
* create by [email protected] on 2018/10/9 13:22
* 第三方平臺使用秒嘀科技
* 控制層實現
**/
@Controller
@RequestMapping("/miao")
public class MiaoDiController {
/**
* 傳送驗證碼
* */
@RequestMapping(value = "/send", method = RequestMethod.GET)
@ResponseBody
public String send(String phone, HttpServletRequest request) throws Exception{
HashMap<String, String> map = IndustrySMS.executeHash(phone);
ObjectMapper objectMapper = new ObjectMapper();
String status = map.get("respCode");
String checkCode = map.get("checkCode");
// 將驗證碼快取到 session 中
HttpSession session = request.getSession();
session.setMaxInactiveInterval(60 * 1); // 設定 session 一分鐘內有效,單位是秒
if (status.trim().equals("00000")) {
map.put("result", "00000");
session.setAttribute("checkCode",checkCode);
} else if(status.trim().equals("00141")) {
map.put("result", "00141");
} else {
map.put("result","fail");
}
return objectMapper.writeValueAsString(map);
}
/**
* 比對校驗碼
* */
@RequestMapping(value = "/checkCode", method = RequestMethod.POST)
@ResponseBody
public String checkCode(String code, HttpServletRequest request) throws Exception{
HashMap<String, String> map = new HashMap<>();
ObjectMapper objectMapper = new ObjectMapper();
HttpSession session = request.getSession(); // 設定 session
String sessionCode = (String)session.getAttribute("checkCode");
if ((code).equals(sessionCode)) { // 和快取比對驗證碼是否相同
map.put("result", "success");
} else {
map.put("result", "fail");
}
return objectMapper.writeValueAsString(map);
}
}
備註:使用秒嘀科技新建簡訊模板時,提供的模板中的逗號是中文的
,免費簡訊較多,可用於除錯,費用較低,技術支援到位,推薦使用。