java实现手机验证码功能

java实现给手机发送验证码,是需要平台的支持的这里我使用的是http://user.ihuyi.com/互亿的短信服务

大家可以注册一个账号http://user.ihuyi.com/register.htmls这里是比较简单的实现大家可以根据自己的需求自行编写


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


/**
 * 验证码发送类
 * @author Administrator
 *
 */
public class sendsms {

	private static String Url = "http://106.ihuyi.com/webservice/sms.php?method=Submit";//提交地址
	private int mobile_code;//发送的验证码
	public int YZM(String SJ){
		
		HttpClient client = new HttpClient(); 
		PostMethod method = new PostMethod(Url);//设置提交地址
		client.getParams().setContentCharset("UTF-8");//设置编码格式
		method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");
		 mobile_code = (int)((Math.random()*9+1)*100000);//产生验证码
	    String content = new String("您的验证码是:" + mobile_code + "。请不要把验证码泄露给其他人。");

		NameValuePair[] data = {//提交短信
			    new NameValuePair("account", "C45591414"), //查看用户名是登录用户中心->验证码短信->产品总览->APIID
			    new NameValuePair("password", "aac9a234fdb8412a694713c0b2e0c9cb"),  //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
			    new NameValuePair("mobile", SJ), //Sj就是手机号码
			    new NameValuePair("content",content),//发送的内容有要求的
		};
		method.setRequestBody(data);//设置提交数据
		try {
			client.executeMethod(method);//提交数据
			/**
			 * 获取返回信息状态
			 */
			String SubmitResult =method.getResponseBodyAsString();
			Document doc = DocumentHelper.parseText(SubmitResult);
			Element root = doc.getRootElement();

			String code = root.elementText("code");//返回的状态信息
//			String msg = root.elementText("msg");
//			String smsid = root.elementText("voiceid");
			 if("2".equals(code)){//2为发送成功
				 JOptionPane.showMessageDialog(null, "发送成功!", "系统提示", 0);
			}
			 else{
				 System.out.println(code);
				 JOptionPane.showMessageDialog(null, "发送失败!", "系统提示", 0);
			 }

		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		//将验证码返回加以判断
		return  mobile_code;
	}
}

然后其他语言或者有什么不懂的可以参照http://www.ihuyi.com/demo/sms/java.html

链接:https://pan.baidu.com/s/12s72PukOQl11FCJu9lNy7w 密码:gpce

猜你喜欢

转载自blog.csdn.net/yjt520557/article/details/83343140