HeavenTang

导航

第三方短信接口使用测试

1、导入包:

// https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient
compile group: 'commons-httpclient', name: 'commons-httpclient', version: '3.1'

2、选一个第三方短信网站
http://sms.webchinese.cn/
3、了解其中短信测试接口
4、测试代码如下:

    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;

    public static void main(String[] args) {
            try {
                String code = sendCode("your phone","xxx","xx");
                System.out.println( code );
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
public static String sendCode(String phone,String content,String code)throws Exception{
    System.out.println("::::::::::::"+code);
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod("http://utf8.api.smschinese.cn");
    post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf8");//在头文件中设置转码
    NameValuePair[] data ={ new NameValuePair("Uid", "注册的用户名"),
            new NameValuePair("Key", "注册后的密钥"),
            new NameValuePair("smsMob",phone),
            new NameValuePair("smsText",content)};
    post.setRequestBody(data);

    client.executeMethod(post);
    Header[] headers = post.getResponseHeaders();
    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("utf-8"));//或gbk
    System.out.println(result); //打印返回消息状态
    post.releaseConnection();
    return result;
}

另外:
若是用于短信注册或登录验证,原理如下:
发送短信验证码的原理是:随机生成一个6位数字,将该6位数字保存到session当中,客户端通过sessionid判断对应的session,用户输入的验证码再与session记录的验证码进行比较。

posted on 2017-09-04 10:27  HeavenTang  阅读(3048)  评论(0编辑  收藏  举报