本文以注册为例,在SpringMVC+Spring+Mybatis框架的基础上完成该短信验证码功能。
发送短信验证码的原理是:随机生成一个6位数字,将该6位数字保存到session当中,客户端通过sessionid判断对应的session,用户输入的验证码再与session记录的验证码进行比较。
复制代码
importjava.util.HashMap;
importorg.apache.commons.httpclient.Header;
importorg.apache.commons.httpclient.HttpClient;
importorg.apache.commons.httpclient.NameValuePair;
importorg.apache.commons.httpclient.methods.PostMethod;
importcom.yuetile.utils.VerifyingCodeGenerator;
public class SendMsg_webchineseController {
public static HashMapgetMessageStatus(String phone)throwsException{
HashMap m=newHashMap();
HttpClient client = newHttpClient();
PostMethod post = newPostMethod("http://gbk.sms.webchinese.cn");
post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在头文件中设置转码
String code=VerifyingCodeGenerator.generate();//验证码
NameValuePair[] data ={ newNameValuePair("Uid", "****"),new NameValuePair("Key","******"),newNameValuePair("smsMob",phone),new NameValuePair("smsText","您正在注册本站会员,本次验证码为:"+code+""+"有效时间为5分钟")};
m.put("code", code);
post.setRequestBody(data);
client.executeMethod(post);
Header[] headers = post.getRespons eHeaders();
intstatusCode = post.getStatusCode();
System.out.println("statusCode:"+statusCode);
for(Header h: headers)
{
System.out.println(h.toString());
}
String result = newString(post.getResponseBodyAsString().getBytes("gbk"));
System.out.println(result); //打印返回消息状态
m.put("result", result);post.releaseConnection();
return m;