暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

使用HttpClient发送短信

码农小黑 2018-12-27
166

没有阿里云短信账号的同学可以选择httpClient方式发送短信

一、注册账号

去中国网建注册一个账号,或者去其他短信网站注册。注册成功后会赠送5条短信,在修改用户信息里填写你的短信签名,发送短信时格式如下:

【短信签名】 短信内容
复制

点击修改短信秘钥,可查看你的短信秘钥,短信接口中需要填写此信息,勿泄露,如图:

二、下载jar包

点击短信API接口,跳转至接口介绍页面,有各种语言发送短信的案例

在 3.JAVA调用案例下面下载jar包

三、java发送短信代码

public static void sendMsg(String phone,String text) throws IOException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod("http://gbk.api.smschinese.cn");
    post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在头文件中设置转码
    NameValuePair[] data ={ new NameValuePair("Uid", "你的登录名"),new NameValuePair("Key", "你的短信秘钥"),new NameValuePair("smsMob",phone),new NameValuePair("smsText",text)};
    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("gbk"));
    System.out.println("打印返回消息状态:"+result); /打印返回消息状态
    post.releaseConnection();
}
复制

main函数发送短信测试

public static void main(String[] args) {
    try {
        sendMsg("176xxxxxxxx","登录验证码为:"800632);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
复制


文章转载自码农小黑,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论