Java实现手机发送短信验证码

1、本功能根据互亿无线短信平台提供的对接接口,需要开通短信服务(可注册领取试用礼包),支持国内国外短信发送,平台连接:点击此连接

2、请求互亿无线短信接口参数说明:(支持get/post请求):

参数名称 参数值描述 是否必填
url 请求路径
account APIID(账户ID)
password APIKEY(账户密码)
mobile 接收人手机号
content 短信内容
time 时间戳(使用动态密码是需填)
format 返回格式(xml或json,默认xml)

3、通过http提交发送短信请求到互亿无线短信服务器后,响应参数(xml格式)如下:

参数名称 类型 描述
code int 返回值为2时,表示提交成功 (code值较多,可根据需要提示msg)
smsid string 当提交成功后,此字段为流水号,否则为0
msg string 提交结果描述

4、示例:

新建一个properties文件,将国内(国际)请求参数配置好(后期改动方便):

sms_url=http://106.ihuyi.cn/webservice/sms.php?method=Submit ##(国内请求路径)
cms_url=http://api.isms.ihuyi.com/webservice/isms.php?method=Submit ##(国外请求路径)
sms_user= admin ##(国内账户ID)
sms_pwd=WEX123 ##(密码)
cms_user=admin  ##(国际账户ID)
cms_pwd=GJCV123 ##(密码)

创建CommonUtils类读取properties文件中的配置信息

/**
 * 
 * 类名称:CommonUtils 
 * 类描述:
 * 创建人:xq
 * 修改备注:
 * @version 
 * 
 */
package com.utils;

import java.io.InputStream;
import java.util.Properties;

/**
 * @ClassName: CommonUtils 
 * @Description: 读取配置文件信息
* written by xq
 * 
 */
public class CommonUtils {

	private static String sms_url;
	
	private static String cms_url;
	
	private static String cms_user;
	
	private static String cms_pwd;

	private static String sms_user;

	private static String sms_pwd;
	
	static {
		try {
			Properties props = new Properties();
			// 加载
			ClassLoader cl = CommonUtils.class.getClassLoader();
			// 读取(properties文件名)
			InputStream is = cl.getResourceAsStream("nets.properties");

			// 加载信息
			props.load(is);
			sms_url = props.getProperty("sms_url");
			cms_url = props.getProperty("cms_url");
			cms_user=props.getProperty("cms_user");
			cms_pwd = props.getProperty("cms_pwd");
			sms_user = props.getProperty("sms_user");
			sms_pwd = props.getProperty("sms_pwd");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
   //提供get/set方法
	public static String getCms_user() {
		return cms_user;
	}

	public static String getCms_pwd() {
		return cms_pwd;
	}

	public static String getCms_url() {
		return cms_url;
	}

	public static String getSms_url() {
		return sms_url;
	}

	public static void setSms_url(String sms_url) {
		CommonUtils.sms_url = sms_url;
	}
	
	public static String getSms_pwd() {
		return sms_pwd;
	}

	public static String getSms_user() {
		return sms_user;
	}
	
	public static void setSms_pwd(String sms_pwd) {
		CommonUtils.sms_pwd = sms_pwd;
	}

	public static void setSms_user(String sms_user) {
		CommonUtils.sms_user = sms_user;
	}
	
}

创建VerifyCode类编写发送短信验证码代码(国际、国内):

package com.agent;

import com.utils.CommonUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Random;

public class VerifyCode {

    public static void main(String[] args) {
        //zone 区分国内国外短信
        getVerifyCode("15000000000","0018");
    }

    /**
     * 添加发送内容
     * @param mobileno
     * @param zone
     * @return
     */
    public static String  getVerifyCode(String mobileno,String zone) {
        // 获取验证码
        String verifycode = String.valueOf(makeRandomWithRange(100000, 999999));
        String s = "86";
        //如果区号不为86开头,说明是国际短信
        String content = "Your verification code is " + verifycode;
        String contents = "您的验证码是:" + verifycode + "。请不要把验证码泄露给其他人。";
        String code="";
        if (zone != null && !zone.equals(s)) {
         code = sendMessage( mobileno, content, zone);
        }else{
          code = sendMessage( mobileno, contents, zone);
        }
        if ("2".equals(code)) {
                return "发送成功";
            } else{
                return "发送失败";
            }
        }

    /**
     * 发送验证码
     * @param mobileno
     * @param content
     * @param zone
     * @return
     */
        public  static String sendMessage(String mobileno, String content,String zone) {
            boolean bclIsSend = false;
            String code = null;
            try {
                StringBuilder sb = new StringBuilder();
                String s="86";
                //国际国内区分
                if(zone!=null&&zone.equals(s)){
                    sb.append(CommonUtils.getSms_url());
                    sb.append("&account=").append(CommonUtils.getSms_user());
                    sb.append("&password=").append(CommonUtils.getSms_pwd());
                    sb.append("&mobile=").append(mobileno);
                }else{
                    sb.append(CommonUtils.getCms_url());
                    sb.append("&account=").append(CommonUtils.getCms_user());
                    sb.append("&password=").append(CommonUtils.getCms_pwd());
                    sb.append("&mobile=").append(zone+"%20"+mobileno);
                }
                String _content = URLEncoder.encode(content, "gbk");
                sb.append("&content=").append(_content.replaceAll("\\+", "%20"));
                String result = httpResult(sb.toString());
                Document doc;
                try {
                    doc = DocumentHelper.parseText(result);
                    Element root = doc.getRootElement();
                    code = root.elementText("code");
                    if ("2".equals(code)) {
                        bclIsSend = true;
                        System.out.println(mobileno + ":----短信提交成功。");
                    }else{
                        System.out.println(mobileno + ":----短信发送失败。");
                    }
                } catch (DocumentException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            return code;
        }

    /**
     * 获取6位验证码
     * @param min
     * @param max
     * @return
     */
    public static int makeRandomWithRange(int min, int max) {
        Random random = new Random();
        int num = random.nextInt(max) % (max - min + 1) + min;
        return num;
    }

    /**
     * 发送请求
     * @param url
     * @return
     */
    public static String httpResult(String url) {
    String result = "";
    try {

        URL reqURL = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) reqURL.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setConnectTimeout(2000);
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String temp = in.readLine();
        while (temp != null) {
            if (result != null) {
                result += temp;
            } else {
                result = temp;
            }

            temp = in.readLine();
        }
        result = URLDecoder.decode(result, "UTF-8");

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return result;
}

    }

猜你喜欢

转载自blog.csdn.net/qq_33914912/article/details/81133044