时间:2022-07-27 11:15:55 | 栏目: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();
}
}
}


