-------1,引入所需要的jar包:commons-codec-1.4.jar;commons-httpclient-3.1.jar;commons-logging-1.1.1.jar
-------2,编写短信发送的Java类
compile('commons-codec:commons-codec:1.12')
compile('commons-httpclient:commons-httpclient:3.1')
compile('commons-logging:commons-logging:1.2')
package com.sms;
import java.io.IOException;
import java.util.Random;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.junit.Test;
public class HttpClientUtil {
public static void main(String[] args) throws Exception {
sendSMS();
}
public static void sendSMS() throws HttpException, IOException{
//短信签名:登录网建后进行设置,在发送的短信验证码中可以看到,表示一个title
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", "thinkers"), new NameValuePair("Key", "d0869dc30085de4f3abb"),
new NameValuePair("smsMob", "13585865081"), new NameValuePair("smsText", "【验证码:+"+getNums()+"】") };
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(getErrorMsg(result)); // 打印返回消息状态
post.releaseConnection();
}
//发送短信后接口返回参数
public static String getErrorMsg(String errorCode){
if("-1".equals(errorCode)){
return "没有该用户账户";
}else if("-2".equals(errorCode)){
return "接口密钥不正确";
}else if("-3".equals(errorCode)){
return "短信数量不足";
}else if("-4".equals(errorCode)){
return "手机号格式不正确";
}else if("-21".equals(errorCode)){
return "MD5接口密钥加密不正确";
}else if("-11".equals(errorCode)){
return "该用户被禁用";
}else if("-14".equals(errorCode)){
return "短信内容出现非法字符";
}else if("-41".equals(errorCode)){
return "手机号码为空";
}else if("-42".equals(errorCode)){
return "短信内容为空";
}else if("-51".equals(errorCode)){
return "短信签名格式不正确";
}else if("-6".equals(errorCode)){
return "IP限制";
}else if("0".equals(errorCode)){
return "短信发送失败";
}else if("1".equals(errorCode)){
return "短信发送成功";
}else{
return "未知错误";
}
}
//随机生成验证码
public static Integer getNums(){
Random random=new Random();
String result="";
int count=4;
for(int i=0;i//从>=0到<10取随机整数
int num=random.nextInt(10);
if(num==0){//如果为0则需要扩大统计的次数
count++;
continue;
}
result=result+""+num;
}
return Integer.valueOf(result);
}
@Test
public void test1(){
System.out.println(getNums());
}
}
------注:网建没有交钱只能免费用3次,3次用完就不会发送短信了