1、增加架包
<!-- 中国网建提供的SMS短信 -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4</version>
</dependency>
2、具体代码
package xk20190810.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
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 class SendMsg {
public static final String NAME = "qq19****2438";// "用 户 名:"非登录用户名
public static final String PWD = "d41************204e980";// "短信密钥"
public PostMethod sendMsg(String phone, Integer code) {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn");
post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码
NameValuePair[] data = {
new NameValuePair("Uid", NAME),
new NameValuePair("Key", PWD),
new NameValuePair("smsMob", phone),
new NameValuePair("smsText", "您的验证码是:" + code + ",60秒内有效,如非本人操作请忽略。")
};
post.setRequestBody(data);
try {
client.executeMethod(post);
} catch (Exception e) {
System.out.println("短信发送异常" + e);
}
return post;
// int statusCode = post.getStatusCode();//获取发送短信请求是否成功结果
// System.out.println("statusCode:" + statusCode);
// Header[] headers = post.getResponseHeaders();//获取请求头信息
// for (Header h : headers) {//遍历头部信息
// System.out.println("h.Str:" + h.toString());
// }
// try {
// String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
// System.out.println("result:" + result);
// } catch (Exception e) {
// System.out.println("获取结果异常" + e);
// }
// post.releaseConnection();//作用是重置request状态位,为下次使用做好准备。
}
public static void main(String[] args) {
SendMsg sm = new SendMsg();
PostMethod post = sm.sendMsg("15882095302", 19960203);
Integer RequestResult = post.getStatusCode();//获取发送短信请求是否成功
try {
String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
System.out.println("发送短信请求结果:" + RequestResult);
System.out.println("短信发送结果:" + result);
post.releaseConnection();//作用是重置request状态位,为下次使用做好准备。
} catch (Exception e) {
System.out.println("获取结果异常" + e);
}
}
}