getCode方法名,其所属类的类名,都可自定义,方法的参数表和能容不能动,在此getCode及下边的getRandumNum都属于CodeUtils工具类 public static String getCode(String postData, String postUrl){ try { //发送POST请求 URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setUseCaches(false); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", "" + postData.length()); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); out.write(postData); out.flush(); out.close(); //获取响应状态 if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { System.out.println("connect failed!"); return ""; } //获取响应内容体 String line, result = ""; BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); while ((line = in.readLine()) != null) { result += line + "\n"; } in.close(); return result; } catch (IOException e) { e.printStackTrace(System.out); } return ""; }
自动生成随机验证码
public static String getRandomNum(){ StringBuffer result = new StringBuffer(); //stringBuilder在jdk1.5以后开始使用速度快,线程不安全,而StringBuffer在jdk1.0开始使用,速度慢,线程安全 for (int i = 0; i <6 ; i++) { result.append(new Random().nextInt(10)); } return result.toString(); }
下面是其方法的调用,数字验证码先存入session,用于用户输入的取出判断,此处可设置2分钟有效,在2分钟后将session的code remove掉即可
getCode方法的调用参数内容根据实际情况决定,第二个参数为短信模板,具体模板参见106jiekou.comhttp://www.106jiekou.com/
request.getSession().setAttribute("code",CodeUtils.getRandomNum()); CodeUtils.getCode("account=106账户&password=106账户登录密码&mobile="+手机号码+"&content=您的验证码是:【"+CodeUtils.getRandomNum()+"】。如需帮助请联系客服。", "http://sms.106jiekou.com/utf8/sms.aspx");