推荐使用:网建. http://sms.webchinese.com.cn/default.shtml
1.Maven导包
<!--发送验证码核心jar包-->
<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
2.准备工具类 (官网也有)
package cn.itsource.pethome.basic.util;
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;
import java.io.IOException;
public class SendMsgUtil {
//本站用户名
private static final String UID = "xiaoshigege";
//接口安全密匙
private static final String KEY = "d41d8cd98f00b204e980";
public static void sendCode(String phone,String text){
PostMethod post = null;
//java也可以像网站一样发送请求
try {
//创建一个客户端
HttpClient client = new HttpClient();
//发送请求地址的url
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", 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); //打印返回消息状态
} catch (IOException e) {
e.printStackTrace();
} finally {
if (post != null) {
//关闭资源
post.releaseConnection();
}
}
}
}
3.Java代码(Service层)
//开始发送短信
SendMsgUtil.sendCode(phone, text);