最近头让我写个发送短信的java程序检测BI系统,检查数据库是否有异常发送,有则发送短信到头的手机里。这里我直说httpclient方式的get请求方式,并且已经有方式的短信的接口了,所以只要再加上参数即可实现,网上有好几种实现方式,我这个比较简单。
具体实现代码如下:
一、get方式
//发送短信Get请求方式
public void sendMSGByGet(String phone) throws HttpException, IOException{
//传递参数
String param = "username="+USR+"&password="+PSD+"&phone="+phone+"&message="+URLEncoder.encode(MSG, "GBK")+"&epid=105250&linkid=&subcode=123";//参数根据实际情况拼装
System.out.println(param);
HttpClient httpClient = new HttpClient();
HttpMethod get = new GetMethod(URLSTR+"?"+param); //get请求方式
get.releaseConnection();
httpClient.executeMethod(get);//发送
String response = get.getResponseBodyAsString(); //取得返回结果
System.out.println(response);
}
以上方式比较简单,需要注意的地方就是短信内容中文编码问题。
二、post方式(这种方式比较普遍)
实现代码如下:
//发送短信post方式
public void sendMSGByPost(String phone) throws HttpException, IOException{
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(URLSTR);
post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在头文件中设置转码
NameValuePair[] data ={ //配置参数
new NameValuePair("username", USR),
new NameValuePair("password", PSD),
new NameValuePair("phone",phone),
new NameValuePair("message",MSG),
new NameValuePair("epid", EPID),
new NameValuePair("linkid",LINKID),
new NameValuePair("subcode",SUBCODE)
};
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();
}
以上方式比较固定,其实很多都是用这种方式,有兴趣的可以试试中国网建的:http://www.smschinese.cn/api.shtml(各种代码示例)