注册网建短信通账号
链接:http://sms.webchinese.cn/
设置短信签名
注意不要乱写别的公司等,会被视为诈骗信息
设置短信密钥,发送时代替密码
Java方式实现
导入依赖 commons-httpclient-3.1.jar
编写SmsUtil工具类
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class SmsUtil {
private String uid;
private String key;
//用于后面的Spring注入方式实现
public int sendSms(String smsMob,String smsTxt ){
return sendSms(this.uid,this.key,smsMob,smsTxt);
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public static void main(String[] args){
int n=sendSms("用户名","密钥","手机号","短信内容");
//如int n=sendSms("abc","55555","11234567574","验证码:8899");
//返回的是发送成功的短信条数
System.out.println("发送成功:"+n);
}
public static int sendSms(String uid,String key,String smsMob,String smsTxt )
{
PostMethod post =null;
try {
HttpClient client = new HttpClient();
post = new PostMethod("http://utf8.api.smschinese.cn");
post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf8");//在头文件中设置转码
NameValuePair[] data = {
new NameValuePair("Uid", uid)
, new NameValuePair("Key", key)
, new NameValuePair("smsMob", smsMob)
, new NameValuePair("smsText", smsTxt)};
post.setRequestBody(data);
client.executeMethod(post);
return Integer.parseInt(post.getResponseBodyAsString());
}catch (Exception ex){
ex.printStackTrace();
throw new RuntimeException(ex);
}
finally {
post.releaseConnection();
}
}
}
前端交互
- 使用Spring进行注入
- 在applicationContext增加配置
- 定义用户名和密钥
编写控制层代码
到此这篇关于Java实现SMS短信通发送手机验证码案例讲解的文章就介绍到这了,更多相关Java实现SMS短信通发送手机验证码内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!