程序調(diào)用飛信API發(fā)送免費(fèi)短信(JAVA例子,其他語(yǔ)言一樣用)
網(wǎng)上看到有網(wǎng)頁(yè)版的飛信,http://fetionlib.appspot.com/ 可以添加好友,群發(fā)和定時(shí)發(fā)送短信給飛信好友,還開(kāi)放了API接口供程序調(diào)用,可以用它來(lái)監(jiān)控機(jī)器是否正常服務(wù)定期給管理員發(fā)短信,或者小規(guī)模的網(wǎng)站給會(huì)員發(fā)短信之類的服務(wù)。
重要提示:近期所有appspot的https都慘遭RESET,請(qǐng)先前使用API的用戶,把調(diào)用地址中https改成http
簡(jiǎn)單測(cè)試一下:http://fetionlib.appspot.com/restlet/fetion/13812345678/password/13912345678/message
其中13812345678 和13912345678是發(fā)送方和接收方的手機(jī)號(hào)碼,注意這兩個(gè)號(hào)碼必須相互是好友,我們把它換成自己的手機(jī)號(hào)碼,讓它發(fā)送給自己,password改成您的密碼,在瀏覽器里輸入該好后的鏈接,稍等片刻,如果成功,便會(huì)顯示OK,此時(shí)您的手機(jī)應(yīng)該能收到自己發(fā)來(lái)的message。
好了,上面是最簡(jiǎn)單的測(cè)試,廢話不多說(shuō)了,下面放Java調(diào)用的例子,來(lái)實(shí)現(xiàn)發(fā)送短信(包括群發(fā)),發(fā)送和取消定時(shí)短信,加好友,取得好友列表等一系列動(dòng)作。其他語(yǔ)言應(yīng)該類似的調(diào)用Http Connection用GET或POST去實(shí)現(xiàn)。下面例子上有注釋,就不多說(shuō)了。
package com.test;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.UUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
/**
*@author Terry Email: yaoxinghuo at 126 dot com
*@version create: Aug 5, 2009 11:17:23 AM
*@version update: Oct 15, 2009 00:11:00 AM
*@description 飛信API(fetionlib) HTTP簡(jiǎn)單調(diào)用舉例 另有Restlet的方式可供調(diào)用。網(wǎng)頁(yè)版飛信首頁(yè):https://fetionlib.appspot.com/
* 小提示:免費(fèi)開(kāi)通飛信:如果您的手機(jī)號(hào)沒(méi)有開(kāi)通飛信,可以到中國(guó)移動(dòng)飛信網(wǎng)站查看開(kāi)通,或者直接編輯短信KTFX發(fā)送到10086開(kāi)通
* 修改飛信密碼:手機(jī)編輯新密碼(6到16位,不能是中文或全角字符)內(nèi)容發(fā)送到12520050
* 直接在瀏覽器里輸入以下地址(您的手機(jī)號(hào)碼和密碼請(qǐng)自行更改,密碼不要包含/,朋友號(hào)碼請(qǐng)?zhí)顚懽约旱氖謾C(jī)號(hào)碼):
* http://fetionlib.appspot.com/restlet/fetion/13812345678/password/13912345678/message
* 以上四個(gè)用/隔開(kāi)的加粗的地方,應(yīng)該分別替換成:您的手機(jī)號(hào)、密碼、對(duì)方手機(jī)號(hào)(可以寫自己的手機(jī)號(hào)發(fā)給自己)、短信內(nèi)容(不超過(guò)180字),
* 如果是密碼錯(cuò)誤,沒(méi)有開(kāi)通飛信,對(duì)方不是您好友等原因不能發(fā)送都是返回提示Message Not Sent,只有成功返回OK
* 如果要發(fā)送中文,最好用URLEncode(UTF-8編碼,如“你好”Encode后為%E4%BD%A0%E5%A5%BD,現(xiàn)已支持)或后面舉的例子(POST方式,注意調(diào)用的URL略有不同)
* 如果您可以收到自己發(fā)給自己的短信,恭喜您,測(cè)試通過(guò),你可以用您熟悉的語(yǔ)言通過(guò)POST或GET調(diào)用,調(diào)用格式請(qǐng)看下面Java例子,其他語(yǔ)言類似
* 如有疑問(wèn)或?qū)PI的接口調(diào)用方式有任何更好的建議,歡迎提出寶貴意見(jiàn)
*
* 現(xiàn)已經(jīng)更新支持取得好友列表、POST方式的群發(fā)(8個(gè)或8個(gè)以下好友)和定時(shí)發(fā)送群發(fā)(定時(shí)群發(fā)最多30個(gè)好友),請(qǐng)看更新的例子
*
* 更新近期發(fā)現(xiàn)有人利用本程序給他人發(fā)送轟炸短信,給他人造成嚴(yán)重騷擾,同時(shí)也大量消耗本站資源,已作如下限制:
* 同一個(gè)手機(jī)號(hào)給同一個(gè)好友的發(fā)短信API以及其他的API(如:添加好友、獲取好友列表等)請(qǐng)求間隔為30秒,30秒內(nèi)的類似請(qǐng)求將無(wú)法完成。
* 注:考慮到實(shí)際需要,給自己發(fā)送短信(手機(jī)號(hào)和對(duì)方好友號(hào)碼相同或者群發(fā)好友里面包含自己手機(jī)號(hào))的API請(qǐng)求將不會(huì)有30秒時(shí)間間隔的限制!
*
* 本飛信API接口程序由Google強(qiáng)力驅(qū)動(dòng)、免費(fèi)托管,將長(zhǎng)期保留,示例程序用到的json包,請(qǐng)到www.json.org下載jar包,也可到這里下載
*/
public class Test {
private static Log log = LogFactory.getLog(Test.class);
public static void main(String[] args) {
//測(cè)試發(fā)短信,注意:相同手機(jī)號(hào),相同好友的請(qǐng)求的調(diào)用間隔要超過(guò)30秒(除非好友中包含你自己的手機(jī)號(hào)),否則不成功(responseCode:406)
boolean b = fetchToSendSMS("13812345678", "12345678", new String[] { "13812345678" },
"TestMessage");
System.out.println("Send Message result:" + b);
//測(cè)試取得好友列表
// JSONArray friends = fetchToGetFriends("13812345678", "12345678");
// System.out.println("friends:\r\n"+ (friends == null ? "null" : friends.toString()));
//測(cè)試添加好友
// int result = fetchToAddFriend("13812345678", "12345678","13812345678","TestMyName", "TestFriendName");
// System.out.println("Add Friend result:"+result);
//測(cè)試發(fā)送定時(shí)短信(注意是太平洋時(shí)間,所以2009-10-09 01:00 是北京時(shí)間09:00發(fā)奧)
// String sid = fetchToSendScheduleMsg("13812345678", "12345678", new String[]{"13912345678"}, "TestScheduleMessage", "2009-10-09 01:00");
// System.out.println("sid:"+sid);
//測(cè)試刪除定時(shí)短信
// boolean b2 = fetchToDeleteScheduleMsg("13812345678", "12345678", new String[]{"aglmZXRpb25saWJyGgsSB0FjY291bnQYAQwLEgdNZXNzYWdlGCQM")};
// System.out.println("schedule message delete result:"+b2);
}
private static final int TRY_TIMES = 3;
private static final int TIME_OUT = 30000;
/**
*發(fā)送短消息 更簡(jiǎn)單的Get方式(不支持群發(fā),如要群發(fā)用下面POST方式,已更新),直接在瀏覽器里輸入以下地址,手機(jī)號(hào)碼和密碼請(qǐng)自行改掉:
* http://fetionlib.appspot.com/restlet/fetion/13812345678/password/13912345678/message 成功返回OK
* 否則返回Message Not Sent,如果要群發(fā)或者您的密碼包含/或者需要提交中文消息避免可能的亂碼最好請(qǐng)用以下的程序(POST方式)
*@param friends
* 短信接收方的好友們
* 注意參數(shù)String[] friends 中的數(shù)組可以是好友的手機(jī)號(hào),也可以是后面用程序取到的好友的uri,詳見(jiàn)后面取得好友列表的說(shuō)明
* 如fetchToSendSMS("13812345678","password",new String[]{"sip:12345678@fetion.com.cn;p=5065","13916416465","tel:15912345678"},"Test");
* 好友數(shù)不能超過(guò)8個(gè),如果有需要,請(qǐng)用程序分開(kāi)來(lái)多次調(diào)用
* 注意:相同手機(jī)號(hào),相同好友的請(qǐng)求的調(diào)用間隔要超過(guò)30秒,否則不成功(responseCode:406),但接受好友中包含你自己的手機(jī)號(hào)的請(qǐng)求不受30秒的限制!
*@param message
* 短信內(nèi)容,字?jǐn)?shù)不能超過(guò)180字
*/
public static boolean fetchToSendSMS(String mobile, String password,
String[] friends, String message) {
// 加上UUID的目的是防止這樣的情況,在服務(wù)器上已經(jīng)成功發(fā)送短信,卻在返回結(jié)果過(guò)程中遇到錯(cuò)誤,
// 而導(dǎo)致客戶端繼續(xù)嘗試請(qǐng)求,此時(shí)讓服務(wù)器根據(jù)UUID分辨出該請(qǐng)求已經(jīng)發(fā)送過(guò),避免再次發(fā)送短信。
String uuid = UUID.randomUUID().toString();
for (int i = 0; i < TRY_TIMES; i++) {
int responseCode = 0;
try {
URL postUrl = new URL(
"http://fetionlib.appspot.com/restlet/fetion");
HttpURLConnection connection = (HttpURLConnection) postUrl
.openConnection();
connection.setConnectTimeout(TIME_OUT);
connection.setReadTimeout(TIME_OUT);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
String content = "mobile=" + mobile + "&uuid=" + uuid
+ "&password=" + password + "&friend=" + convertArrayToJSONString(friends)
+ "&message=" + URLEncoder.encode(message, "utf-8");
out.writeBytes(content);
out.flush();
out.close();
responseCode = connection.getResponseCode();
connection.disconnect();
if (responseCode == 202)
return true;
else
return false;
} catch (Exception e) {
log.warn("error fetchToSendSMS, exception:" + e.getMessage()
+ ". tried " + i + " times");
}
}
return false;
}
/**
*取得好友列表 GET方式為:
* http://fetionlib.appspot.com/restlet/fetion/friendsList/13812345678/password
* 成功將返回JSON格式的好友列表,如果您不了解JSON格式,請(qǐng)先網(wǎng)上查閱相關(guān)知識(shí),
* 如:[{"nickname":"Jerry","localname":"小張","uri":"sip:123456@fetion.com.cn;p=6012","mobile":"13912345678"}]
* 其中nickname是對(duì)方給自己設(shè)置的昵稱,localname是您給對(duì)方設(shè)置的名字,mobile是對(duì)方公開(kāi)的手機(jī)號(hào),uri是該用戶的標(biāo)識(shí)符,可用于發(fā)送短信時(shí)傳遞的參數(shù)
* 注意nickname、localname、mobile 這三個(gè)字段可能為空,如果為空,將不會(huì)再JSON中顯示!
* 不成功返回空白
* 注意:相同手機(jī)號(hào)調(diào)用間隔要超過(guò)30秒,否則不成功(responseCode:406)
*
* 您從JSONArray中取得的uri,如sip:123456@fetion.com.cn;p=6012或可能為tel:13912345678,
* 可直接作為參數(shù)傳入上面的例子中發(fā)送短信, 如果有mobile,也可以傳入mobile如13916416465,
* 不過(guò)有些時(shí)候,對(duì)方不公開(kāi)手機(jī)號(hào),便無(wú)法獲取手機(jī)號(hào),只有通過(guò)uri來(lái)發(fā)送短信
*
*/
public static JSONArray fetchToGetFriends(String mobile, String password) {
String uuid = UUID.randomUUID().toString();
for (int i = 0; i < TRY_TIMES; i++) {
try {
URL postUrl = new URL(
"http://fetionlib.appspot.com/restlet/fetion/friendsList");
HttpURLConnection connection = (HttpURLConnection) postUrl
.openConnection();
connection.setConnectTimeout(TIME_OUT);
connection.setReadTimeout(TIME_OUT);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
String content = "mobile=" + mobile + "&uuid=" + uuid
+ "&password=" + password;
out.writeBytes(content);
out.flush();
out.close();
int responseCode = connection.getResponseCode();
if (responseCode == 202) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream())); // 讀取結(jié)果
StringBuffer sb = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
connection.disconnect();
return new JSONArray(sb.toString());
} else {
connection.disconnect();
}
} catch (Exception e) {
log.warn("error fetchToGetFriends, exception:" + e.getMessage()
+ ". tried " + i + " times");
}
}
return null;
}
/**
*邀請(qǐng)好友 GET方式為:
* http://fetionlib.appspot.com/restlet/fetion/friend/13812345678/password/13912345678/MyName/FriendNickname 返回?cái)?shù)字-1或0或1,見(jiàn)下面說(shuō)明
*
*@param friend
* 被邀請(qǐng)好友的手機(jī)號(hào)
*@param desc
* 您的姓名(不能超過(guò)10個(gè)字),對(duì)方收到邀請(qǐng)短信時(shí),會(huì)顯示這個(gè)名字,以便讓對(duì)方知道您是誰(shuí)
*@param nickname
* 對(duì)方的姓名(不能超過(guò)10個(gè)字),如果對(duì)方同意的話,這個(gè)名字會(huì)作為您的好友名稱顯示
*
*@return -1錯(cuò)誤或者對(duì)方手機(jī)號(hào)不支持, 0對(duì)方已經(jīng)是您的好友 1成功發(fā)送邀請(qǐng)短信,等待對(duì)方回復(fù)是否同意
* 注意:相同手機(jī)號(hào)調(diào)用間隔要超過(guò)30秒,否則不成功(responseCode:406)
*/
public static int fetchToAddFriend(String mobile, String password,
String friend, String desc, String nickname) {
String uuid = UUID.randomUUID().toString();
for (int i = 0; i < TRY_TIMES; i++) {
int responseCode = 0;
try {
URL postUrl = new URL(
"http://fetionlib.appspot.com/restlet/fetion/friend");
HttpURLConnection connection = (HttpURLConnection) postUrl
.openConnection();
connection.setConnectTimeout(TIME_OUT);
connection.setReadTimeout(TIME_OUT);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
String content = "mobile=" + mobile + "&uuid=" + uuid
+ "&password=" + password + "&friend=" + friend
+ "&desc=" + URLEncoder.encode(desc, "utf-8")
+ "&nickname=" + URLEncoder.encode(nickname, "utf-8");
out.writeBytes(content);
out.flush();
out.close();
responseCode = connection.getResponseCode();
if (responseCode == 202) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream())); // 讀取結(jié)果
StringBuffer sb = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
connection.disconnect();
JSONObject jo = new JSONObject(sb.toString());
return jo.getInt("action");
} else {
connection.disconnect();
return -1;
}
} catch (Exception e) {
log.warn("error fetchToAddFriend, exception:" + e.getMessage()
+ ". tried " + i + " times");
}
}
return -1;
}
/**
*發(fā)送定時(shí)短信 GET方式為(不支持群發(fā),如要群發(fā)用下面POST方式,已更新):
* http://fetionlib.appspot.com/restlet/fetion/schedule/13812345678/password/13912345678/message/2009-08-08%2012:18 成功返回sid號(hào)碼,否則返回空白(空格)
*
*POST方式如下
*
*@param message
* 短信內(nèi)容,字?jǐn)?shù)不能超過(guò)180字
*@param date
* 發(fā)送日期格式為yyyy-MM-dd HH:mm,注意日期為時(shí)區(qū)為0的標(biāo)準(zhǔn)時(shí)間,北京時(shí)間的時(shí)區(qū)是8,所以要減去8小時(shí);
* 如計(jì)劃2009-08-08 20:18分發(fā)送,應(yīng)該填寫2009-08-08 12:18;
* 中國(guó)移動(dòng)還規(guī)定日期要超出現(xiàn)在時(shí)間20分鐘但不能超過(guò)1年。
*@param friends
* 接受短信的好友們, 其中的數(shù)組可以是好友的手機(jī)號(hào),也可以是用程序取到的好友的uri,注意好友數(shù)不能超過(guò)30個(gè),如果有需要,請(qǐng)用程序分開(kāi)來(lái)多次調(diào)用
* 注意:相同手機(jī)號(hào),相同好友的請(qǐng)求的調(diào)用間隔要超過(guò)30秒,否則不成功(responseCode:406),但接受好友中包含你自己的手機(jī)號(hào)的請(qǐng)求不受30秒的限制!
*
*@return 一個(gè)sid號(hào)碼,記下來(lái)如果后續(xù)要撤銷短信發(fā)送,需要用到這個(gè)號(hào)碼
*/
public static String fetchToSendScheduleMsg(String mobile, String password,
String[] friends, String message, String date) {
String uuid = UUID.randomUUID().toString();
for (int i = 0; i < TRY_TIMES; i++) {
try {
URL postUrl = new URL(
"http://fetionlib.appspot.com/restlet/fetion/schedule");
HttpURLConnection connection = (HttpURLConnection) postUrl
.openConnection();
connection.setConnectTimeout(TIME_OUT);
connection.setReadTimeout(TIME_OUT);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
String content = "mobile=" + mobile + "&uuid=" + uuid
+ "&password=" + password + "&friend=" + convertArrayToJSONString(friends)
+ "&schedule=" + date.replace(" ", "%20") + "&message="
+ URLEncoder.encode(message, "utf-8");
out.writeBytes(content);
out.flush();
out.close();
int responseCode = connection.getResponseCode();
if (responseCode == 202) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream())); // 讀取結(jié)果
StringBuffer sb = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
connection.disconnect();
JSONObject jo = new JSONObject(sb.toString());
return jo.getString("sid");
} else {
connection.disconnect();
return null;
}
} catch (Exception e) {
log.warn("error fetchToSaveSchedule, exception:"
+ e.getMessage() + ". tried " + i + " times");
}
}
return null;
}
/**
*刪除定時(shí)短信 GET方式為:
* http://fetionlib.appspot.com/restlet/fetion/scheduleDelete/13812345678/password/aglmZXRpb25saWJyGgsSB0FjY291bnQYAQwLEgdNZXNzYWdlGCQM
* aglmZXRpb25saWJyGgsSB0FjY291bnQYAQwLEgdNZXNzYWdlGCQM是你發(fā)送定時(shí)短信返回的sid號(hào)碼,
* GET方式之支持一次刪除一個(gè)定時(shí)短信, 如果要?jiǎng)h除多個(gè),請(qǐng)用下面的POST方式,成功返回OK,否則返回Schedule Not Deleted
* 注意:相同手機(jī)號(hào)調(diào)用間隔要超過(guò)30秒,否則不成功(responseCode:406)
*
*@param sid
* 發(fā)送定時(shí)短信時(shí)返回的那些sid號(hào)碼(不能超過(guò)10個(gè)sid),多個(gè)用數(shù)組的形式,程序會(huì)轉(zhuǎn)換成JSON提交
*
*/
public static boolean fetchToDeleteScheduleMsg(String mobile,
String password, String[] sids) {
String uuid = UUID.randomUUID().toString();
for (int i = 0; i < TRY_TIMES; i++) {
try {
URL postUrl = new URL(
"http://fetionlib.appspot.com/restlet/fetion/scheduleDelete");
HttpURLConnection connection = (HttpURLConnection) postUrl
.openConnection();
connection.setConnectTimeout(TIME_OUT);
connection.setReadTimeout(TIME_OUT);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
String content = "mobile=" + mobile + "&uuid=" + uuid
+ "&password=" + password + "&sids="
+ convertArrayToJSONString(sids);
out.writeBytes(content);
out.flush();
out.close();
int responseCode = connection.getResponseCode();
connection.disconnect();
if (responseCode == 202)
return true;
else
return false;
} catch (Exception e) {
log.warn("error fetchToDeleteSchedule, exception:"
+ e.getMessage() + ". tried " + i + " times");
}
}
return false;
}
//把數(shù)組轉(zhuǎn)化成JSONString
private static String convertArrayToJSONString(String[] arr) throws Exception {
JSONArray ja = new JSONArray();
for (String a : arr)
ja.put(a);//ja.add(a);//?
return URLEncoder.encode(ja.toString(), "UTF-8");
}
}
posted on 2009-09-25 05:48 itcontent 閱讀(979) 評(píng)論(0) 編輯 收藏