java後臺呼叫簡訊介面,實現傳送簡訊驗證碼的控制層實現
阿新 • • 發佈:2018-12-30
1.設計:使用者填寫手機號,點選獲取驗證碼按鈕,controller層獲得所要傳送驗證碼的手機號,隨機生成六位數的驗證碼。呼叫傳送簡訊介面url向此手機號傳送驗證碼。注意:下面的程式碼採用的是雲信使的簡訊驗證碼介面,不同的驗證碼更換不同的url格式,即可。
`
@RequestMapping(value = "/sendValidate") public void sendValidate(HttpServletRequest request,HttpServletResponse response) throws MalformedURLException { String vcode = ""; String phonenumber = request.getParameter("phonenumber"); URL url; String str = null; JSONObject json = new JSONObject(); //生成驗證碼 for (int i = 0; i < 6; i++) { vcode = vcode + (int) (Math.random() * 9); } User us = userService.getUserMessage(phonenumber); if (us != null) { json.put("status", -2);// 電話號碼已被註冊過 try { ResponseUtil.write(response, json.toString()); } catch (Exception e1) { } return; } try { url = new URL( "http://api.sms.cn/sms/?ac=send&uid=使用者名稱&pwd=你註冊時md5加密的密碼&template=100006&mobile="+phonenumber+"&content={code:"+vcode+"}"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); DataInputStream read= new DataInputStream(connection.getInputStream()); str = read.readUTF(); } catch (Exception e) { json.put("status", -1);// 伺服器端錯誤,例如沒網了 try { ResponseUtil.write(response, json.toString()); } catch (Exception e1) { } return; } if (str != null && str.substring(6, 9).equals("100") == true) { json.put("status", 1);// 驗證碼傳送成功 } else json.put("status", 0);// 驗證碼傳送失敗 try { ResponseUtil.write(response, json.toString()); } catch (Exception e) { e.printStackTrace(); } }`