Java註冊手機獲取驗證碼
阿新 • • 發佈:2019-02-19
註冊傳送手機驗證碼:
@RequestMapping(value = "/register/sendCode", method = RequestMethod.POST) public ResponseEntity<AjaxPostResponse> sendCode(HttpServletRequest request, HttpServletResponse response) { String schoolId = this.getSchoolId(request); String mobile = ServletRequestUtils.getStringParameter(request, "mobile", "").trim(); if (StringUtils.isBlank(mobile)) { return this.errorResponse("手機號不能為空"); } Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$"); Matcher m = p.matcher(mobile); if (false == m.matches()) { return this.errorResponse("手機號格式不正確"); } User user = userManager.getUserByMobile(schoolId, mobile); if (null != user) { return this.errorResponse("該手機號已註冊"); } School school = schoolManager.getSchool(schoolId); SchoolSettings schoolSettings = school.getSchoolSettingsBean(); Integer sendTime = 0; // 預防簡訊轟炸 sendTime = memcachedClient.get("mobileCode_" + mobile) == null ? 0 : (Integer) memcachedClient.get("mobileCode_" + mobile); if (0 == sendTime) { memcachedClient.add("mobileCode_" + mobile, 30 * 60, sendTime); // 30 minutes } if (5 < sendTime) { return this.errorResponse("獲取驗證碼次數過多"); } if (YesNoStatus.YES.getValue().equals(schoolSettings.getRegisterSetting())) { String serviceURL = schoolSettings.getActivationMobileUrl(); String sn = schoolSettings.getActivationMobileSn(); String password = schoolSettings.getActivationMobilePassword(); String content = schoolSettings.getActivationMobileContent(); String code = PrimaryKeyUtils.generateRandomKey().substring(0, 4); request.getSession().setAttribute("mobile_code"+mobile, code); content = content.replaceAll("\\$\\{schoolName\\}", school.getName()); content = content.replaceAll("\\$\\{mobile\\}", mobile); content = content.replaceAll("\\$\\{verificationCode\\}", code); try { MobileServerUtils.sendMobileCode(mobile, serviceURL, sn, password, content); } catch (UnsupportedEncodingException e) { logger.info("RegisterController UnsupportedEncodingException", e); } // 把請求驗證碼次數儲存到MemCached中 try { String key = "mobileCode_" + mobile; sendTime++; memcachedClient.replace(key, 30 * 60, sendTime); // 30 minutes } catch (Exception e) { logger.warn("把使用者資訊儲存在Memcached中時發生異常,Cause: ", e); } return this.okResponse(true); } return this.errorResponse("暫不開放註冊"); }
傳送手機驗證碼的處理類:
package com.school.util; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 手機驗證碼工具類 * @author FeiFan Lin */ public class MobileServerUtils { private static final Logger LOG = LoggerFactory.getLogger(MobileServerUtils.class); private String serviceURL = ""; private String sn = ""; // 序列號 private String password = ""; private String pwd = "";// 密碼 /* * 建構函式 */ private MobileServerUtils(String serviceURL, String sn, String password) throws UnsupportedEncodingException { this.serviceURL = serviceURL; this.sn = sn; this.password = password; // 密碼為md5(sn+password) this.pwd = this.getMD5(sn + password); } /** * 傳送驗證碼到手機 * @param mobile 手機號 * @param serviceURL 手機平臺伺服器地址 * @param sn 序列號 * @param password 密碼 * @param content 內容 * @return 唯一標識 * @throws UnsupportedEncodingException */ public static String sendMobileCode(String mobile, String serviceURL, String sn, String password, String content) throws UnsupportedEncodingException { MobileServerUtils ms = new MobileServerUtils(serviceURL, sn, password); content = URLEncoder.encode(content, "utf8"); String result_mt = ms.mdsmssend(mobile, content, "", "", "", ""); return result_mt; } /* * 方法名稱:getMD5 * 功 能:字串MD5加密 * 參 數:待轉換字串 * 返 回 值:加密之後字串 */ private String getMD5(String sourceStr) throws UnsupportedEncodingException { String resultStr = ""; try { byte[] temp = sourceStr.getBytes(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(temp); // resultStr = new String(md5.digest()); byte[] b = md5.digest(); for (int i = 0; i < b.length; i++) { char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char[] ob = new char[2]; ob[0] = digit[(b[i] >>> 4) & 0X0F]; ob[1] = digit[b[i] & 0X0F]; resultStr += new String(ob); } return resultStr; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /* * 方法名稱:mdgetSninfo * 功 能:獲取資訊 * 參 數:sn,pwd(軟體序列號,加密密碼md5(sn+password)) * */ private String mdgetSninfo() { String result = ""; String soapAction = "http://entinfo.cn/mdgetSninfo"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"; xml += "<soap:Body>"; xml += "<mdgetSninfo xmlns=\"http://entinfo.cn/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + pwd + "</pwd>"; xml += "</mdgetSninfo>"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern.compile("<mdgetSninfoResult>(.*)</mdgetSninfoResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } return result; } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名稱:mdgxsend * 功 能:傳送個性簡訊 * 參 數:mobile,content,ext,stime,rrid,msgfmt(手機號,內容,擴充套件碼,定時時間,唯一標識,內容編碼) * 返 回 值:唯一標識,如果不填寫rrid將返回系統生成的 */ private String mdgxsend(String mobile, String content, String ext, String stime, String rrid, String msgfmt) { String result = ""; String soapAction = "http://entinfo.cn/mdgxsend"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"; xml += "<soap:Body>"; xml += "<mdgxsend xmlns=\"http://entinfo.cn/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + pwd + "</pwd>"; xml += "<mobile>" + mobile + "</mobile>"; xml += "<content>" + content + "</content>"; xml += "<ext>" + ext + "</ext>"; xml += "<stime>" + stime + "</stime>"; xml += "<rrid>" + rrid + "</rrid>"; xml += "<msgfmt>" + msgfmt + "</msgfmt>"; xml += "</mdgxsend>"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern.compile("<mdgxsendResult>(.*)</mdgxsendResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } return result; } catch (Exception e) { e.printStackTrace(); return ""; } } /** * 方法名稱:mdsmssend * 功 能:傳送簡訊 * @param mobile 手機號 * @param content 內容 * @param ext 擴充套件碼 * @param stime 定時時間 * @param rrid 唯一標識 * @param msgfmt 內容編碼 * @return 唯一標識,如果不填寫rrid將返回系統生成的 */ private String mdsmssend(String mobile, String content, String ext, String stime, String rrid,String msgfmt) { String result = ""; String soapAction = "http://entinfo.cn/mdsmssend"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"; xml += "<soap:Body>"; xml += "<mdsmssend xmlns=\"http://entinfo.cn/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + pwd + "</pwd>"; xml += "<mobile>" + mobile + "</mobile>"; xml += "<content>" + content + "</content>"; xml += "<ext>" + ext + "</ext>"; xml += "<stime>" + stime + "</stime>"; xml += "<rrid>" + rrid + "</rrid>"; xml += "<msgfmt>" + msgfmt + "</msgfmt>"; xml += "</mdsmssend>"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); //bout.write(xml.getBytes()); bout.write(xml.getBytes("GBK")); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern.compile("<mdsmssendResult>(.*)</mdsmssendResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } return result; } catch (Exception e) { e.printStackTrace(); return ""; } } }
跟通訊運營商開通發簡訊服務:
會有
"activationMobilePassword": 密碼--通訊運營商提供的
"activationMobileSn": 序列號--通訊運營商提供的
"activationMobileUrl": 簡訊服務介面---通訊運營商提供的
下面的是自己編輯的 簡訊的內容:驗證碼、
"activationMobileContent":"${verificationCode} (${schoolName}註冊驗證碼,五分鐘內有效)【${schoolName}】",
"forgotPasswordTitle":"${nickname},請重置您${schoolName}的登入密碼",
"forgotPasswordContent":"Hi, ${nickname} \r