java短信发送,验证功能

使用短信接口发送消息是非常简单的一些操作,找到短信经销商后,他们会给我们提供一些短信提交接口说明文档和短信提交DEMO,首先不要着急查看短信提交DEMO,先查看短信接口文档,他们会有一个短信接口地址,以及短信调取的方法,方法中包含需要传递的参数。看明白后,再查看DEMO这样就简单多了。

下面是我在项目中发送短信验证码的例子,仅供参考:

如何生成验证码参考:http://blog.csdn.net/smilejuan/article/details/52251103文章

首先有一个发送短信的封装方法:

/**
	 * 发送短息接口
	 * @param postData   发送短信的参数
	 * @param postUrl    发送路径及调用方法
	 * @return
	 */
	   public static String SMS(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 "";
	    }

封装好该方法后,在controller调用,并解析接口返回信息,判断短信是否发送成功

//发送短信
String PostData = "sname=DL-wangan12&spwd=wangan12&scorpid=&sprdid=1012818&sdst="+telephone+"&smsg="+java.net.URLEncoder.encode("您的验证码是:"+code+"【xxx】","utf-8");
String ret =this.SMS(PostData, "http://cf.lmobile.cn/submitdata/Service.asmx/g_Submit");
Document doc = null;
doc = DocumentHelper.parseText(ret); // 将字符串转为XML  
Element rootElt = doc.getRootElement(); // 获取根节点  
//获取根节点下的子节点
Element eName = rootElt.element("State"); 
 //节点内容
 String name=eName.getTextTrim();
if(name.equals("0")){
	 System.out.println("短信发送成功了");
 }else{
         System.out.println("短信发送失败了");
}


 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值