SMS平台发短信的代码

首先去SMS注册一下,得到用户名和密钥。然后用以下代码,即可以发短信了。http://sms.webchinese.cn/api.shtml

package com.SmsTest.Test;
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.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
/** author:利用SMS平台发送短信*/
public class SendMsg {public SendMsg(){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","此乃测试SMS手机发送平台的短信,为代码自动发出。【签名】")};post.setRequestBody(data);try {client.executeMethod(post);} catch (HttpException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}Header[] headers = post.getResponseHeaders();int statusCode = post.getStatusCode();System.out.println("statusCode:"+statusCode);for(Header h : headers){System.out.println(h.toString());}String result = "";try {result = new String(post.getResponseBodyAsString().getBytes("gbk"));} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} System.out.println(result);post.releaseConnection();}public static void main(String[] args){SendMsg msg = new SendMsg();}
}

需要注意几点:

1.注册后,在代码中填入自己的用户名和密钥,记住是密钥,不是密码。在SMS的页面上可以查看到密钥,自己找找。

2.需要导入HttpClient的几个jar包。

3.只能免费发5条短信,如果还需用,就需要充钱。

反正很方便就是了,在需要有短信功能的系统中可以用到。

Published by

风君子

独自遨游何稽首 揭天掀地慰生平