本文以注册为例,在SpringMVC+Spring+Mybatis框架的基础上完成该短信验证码功能。
发送短信验证码的原理是:随机生成一个6位数字,将该6位数字保存到session当中,客户端通过sessionid判断对应的session,用户输入的验证码再与session记录的验证码进行比较。
复制代码
import java.util.HashMap;
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 com.yuetile.utils.VerifyingCodeGenerator;
public class SendMsg_webchineseController {
public static HashMap getMessageStatus(String phone)throws Exception{
HashMap m=new HashMap();
HttpClient client = new HttpClient();
PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn");
post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在头文件中设置转码
String code=VerifyingCodeGenerator.generate();//验证码
NameValuePair[] data ={ new NameValuePair("Uid", ""),new NameValuePair("Key", "**"),new NameValuePair("smsMob",phone),new NameValuePair("smsText","您正在注册本站会员,本次验证码为:"+code+""+"有效时间为5分钟")};
m.put("code", code);
post.setRequestBody(data);
client.executeMethod(post);
Header[] headers = post.getRespons eHeaders();
int statusCode = post.getStatusCode();
System.out.println("statusCode:"+statusCode);
for(Header h : headers)
{
System.out.println(h.toString());
}
String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
System.out.println(result); //打印返回消息状态
m.put("result", result);post.releaseConnection();
return m;
本文介绍如何在SpringMVC+Spring+Mybatis框架下实现手机验证码功能。首先随机生成6位数字验证码并存入session,用户输入的验证码与session中的验证码进行比对。具体步骤包括调用HttpClient发送POST请求到第三方短信平台,携带Uid、Key、手机号和验证码内容进行发送。
4661

被折叠的 条评论
为什么被折叠?



