java发送短信,调用第三方的接口。
方式有很多种,短信猫,移动运营商,中国网建等等,这里采用中国网建
贴上代码:
jar包下载
commons-logging-1.1.1.jar
commons-httpclient-3.1.jar
commons-codec-1.4.jar
1,首先要去中国网建注册一个帐号,帐号和key在发送短信的时候会用到
2,程序代码
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_webchinese {
public static void main(String[] args)throws Exception
{
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", "本站用户名"),new NameValuePair("Key", "接口安全密码"),new NameValuePair("smsMob","手机号码"),new NameValuePair("smsText","短信内容")};
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);
post.releaseConnection();
}
}
示例工程: