本例是通過使用中國網建提供的SMS短信平台(申請账號地址:http://sms.webchinese.cn/default.shtml)實現

Demo.java:

package com.cz.message;

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;

public class Demo {
	public static void main(String[] args) {
		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod("http://sms.webchinese.cn/web_api/");
		post.addRequestHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=gbk");// 在頭文件中設置轉碼
		NameValuePair[] data = { new NameValuePair("Uid", "*****"), // 注冊的用戶名
				new NameValuePair("Key", "*****"), // 短信api接口下的key密鑰,不是你的登錄密碼
				new NameValuePair("smsMob", "*****"), // 手機號碼
				new NameValuePair("smsText", "java程序發的信息!!") };
		post.setRequestBody(data);

		try {
			client.executeMethod(post);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.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 = null;
		try {
			result = new String(post.getResponseBodyAsString().getBytes(
					"gbk"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		System.out.println(result);
		post.releaseConnection();
	}

}

 

運行本程序首先的代入三個jar包:
commons-codec-1.4
commons-httpclient-3.1
commons-logging-1.1.1

創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()