天天看點

Java代碼實作SMS短信發送功能

使用中國建網提供的SMS短信平台實作,登入http://sms.webchinese.cn/reg.shtml注冊後,可以免費獲得3條彩信和5條短信的使用。具體代碼如下:

/*
     * 通過SMS平台發送短信
     */ 
    @RequestMapping(value="/sendSmsMessage.do",produces="text/xml;charset=UTF-8")
    @ResponseBody
    public String sendSmsMessage(HttpServletRequest request){  
        String content = request.getParameter("msgPhone");
        HttpClient client = new HttpClient();  
        PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn");  
        // 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", "wuyijun"),// 注冊的使用者名
                new NameValuePair("Key", "d0208c4bfdcbac873f43"),// 注冊成功後,登入網站後得到的密鑰  
                new NameValuePair("smsMob", "18850528496"),// 手機号碼  
                new NameValuePair("smsText", content) };// 短信内容  
        post.setRequestBody(data);  
  
        try {
		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);
	        return "success";
	} catch (HttpException e) {
		return e.getMessage();
	} catch (IOException e) {
		return e.getMessage();
	}  
    }
           

需要用到的jar包共三個:

commons-logging-1.1.1.jar

commons-httpclient-3.1.jar

commons-codec-1.4.jar

中國建網SMS短信通API :

GBK編碼發送接口位址:

http://gbk.sms.webchinese.cn/?Uid=本站使用者名&Key=接口安全密碼&smsMob=手機号碼&smsText=短信内容

UTF-8編碼發送接口位址:

http://utf8.sms.webchinese.cn/?Uid=本站使用者名&Key=接口安全密碼&smsMob=手機号碼&smsText=短信内容

擷取短信數量接口位址(UTF8):

http://sms.webchinese.cn/web_api/SMS/?Action=SMS_Num&Uid=本站使用者名&Key=接口安全密

擷取短信數量接口位址(GBK):

http://sms.webchinese.cn/web_api/SMS/GBK/?Action=SMS_Num&Uid=本站使用者名&Key=接口安全密碼

提示:HTTP調用URL接口時, 參數值必須URL編碼後再調用

參數變量 說明
Gbk編碼Url http://gbk.sms.webchinese.cn/
Utf-8編碼Url http://utf8.sms.webchinese.cn/
Uid 本站使用者名(如您無本站使用者名請先注冊)
Key 注冊時填寫的接口安全密碼(可到使用者平台修改安全密碼)
smsMob 目的手機号碼(多個手機号請用半形逗號隔開)
smsText 短信内容,最多支援300個字,普通短信70個字/條,長短信64個字/條計費

多個手機号請用半角,隔開,如:13888888886,13888888887,1388888888 一次最多對50個手機發送

短信内容支援長短信,最多300個字,普通短信70個字/條,長短信64個字/條計費

短信發送後傳回值 說 明
-1 沒有該使用者賬戶
-2 密鑰不正确(不是使用者密碼)
-3 短信數量不足
-11 該使用者被禁用
-14 短信内容出現非法字元
-4 手機号格式不正确
-41 手機号碼為空
-42 短信内容為空
大于0 短信發送數量