itcontent

          常用鏈接

          統計

          最新評論

          程序調用飛信API發送免費短信(JAVA例子,其他語言一樣用)


          網上看到有網頁版的飛信,http://fetionlib.appspot.com/ 可以添加好友,群發和定時發送短信給飛信好友,還開放了API接口供程序調用,可以用它來監控機器是否正常服務定期給管理員發短信,或者小規模的網站給會員發短信之類的服務。

          重要提示:近期所有appspot的https都慘遭RESET,請先前使用API的用戶,把調用地址中https改成http

          簡單測試一下:http://fetionlib.appspot.com/restlet/fetion/13812345678/password/13912345678/message

          其中13812345678 和13912345678是發送方和接收方的手機號碼,注意這兩個號碼必須相互是好友,我們把它換成自己的手機號碼,讓它發送給自己,password改成您的密碼,在瀏覽器里輸入該好后的鏈接,稍等片刻,如果成功,便會顯示OK,此時您的手機應該能收到自己發來的message。

          好了,上面是最簡單的測試,廢話不多說了,下面放Java調用的例子,來實現發送短信(包括群發),發送和取消定時短信,加好友,取得好友列表等一系列動作。其他語言應該類似的調用Http Connection用GET或POST去實現。下面例子上有注釋,就不多說了。


          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簡單調用舉例 另有Restlet的方式可供調用。網頁版飛信首頁:https://fetionlib.appspot.com/
           *              小提示:免費開通飛信:如果您的手機號沒有開通飛信,可以到中國移動飛信網站查看開通,或者直接編輯短信KTFX發送到10086開通
           *              修改飛信密碼:手機編輯新密碼(6到16位,不能是中文或全角字符)內容發送到12520050
           *              直接在瀏覽器里輸入以下地址(您的手機號碼和密碼請自行更改,密碼不要包含/,朋友號碼請填寫自己的手機號碼):
           *              http://fetionlib.appspot.com/restlet/fetion/13812345678/password/13912345678/message
           *              以上四個用/隔開的加粗的地方,應該分別替換成:您的手機號、密碼、對方手機號(可以寫自己的手機號發給自己)、短信內容(不超過180字),
           *              如果是密碼錯誤,沒有開通飛信,對方不是您好友等原因不能發送都是返回提示Message Not Sent,只有成功返回OK
           *              如果要發送中文,最好用URLEncode(UTF-8編碼,如“你好”Encode后為%E4%BD%A0%E5%A5%BD,現已支持)或后面舉的例子(POST方式,注意調用的URL略有不同)
           *              如果您可以收到自己發給自己的短信,恭喜您,測試通過,你可以用您熟悉的語言通過POST或GET調用,調用格式請看下面Java例子,其他語言類似
           *              如有疑問或對API的接口調用方式有任何更好的建議,歡迎提出寶貴意見
           * 
           *              現已經更新支持取得好友列表、POST方式的群發(8個或8個以下好友)和定時發送群發(定時群發最多30個好友),請看更新的例子
           * 
           *              更新近期發現有人利用本程序給他人發送轟炸短信,給他人造成嚴重騷擾,同時也大量消耗本站資源,已作如下限制:
           *              同一個手機號給同一個好友的發短信API以及其他的API(如:添加好友、獲取好友列表等)請求間隔為30秒,30秒內的類似請求將無法完成。
           *              注:考慮到實際需要,給自己發送短信(手機號和對方好友號碼相同或者群發好友里面包含自己手機號)的API請求將不會有30秒時間間隔的限制!
           * 
           *              本飛信API接口程序由Google強力驅動、免費托管,將長期保留,示例程序用到的json包,請到www.json.org下載jar包,也可到這里下載
           */
          public class Test {
              private static Log log = LogFactory.getLog(Test.class);

              public static void main(String[] args) {
                  //測試發短信,注意:相同手機號,相同好友的請求的調用間隔要超過30秒(除非好友中包含你自己的手機號),否則不成功(responseCode:406)
                  boolean b = fetchToSendSMS("13812345678", "12345678", new String[] { "13812345678" },
                          "TestMessage");
                  System.out.println("Send Message result:" + b);

                  //測試取得好友列表
                  // JSONArray friends = fetchToGetFriends("13812345678", "12345678");
                  // System.out.println("friends:\r\n"+ (friends == null ? "null" : friends.toString()));

                  //測試添加好友
                  // int result = fetchToAddFriend("13812345678", "12345678","13812345678","TestMyName", "TestFriendName");
                  // System.out.println("Add Friend result:"+result);

                  //測試發送定時短信(注意是太平洋時間,所以2009-10-09 01:00 是北京時間09:00發奧)
                  // String sid = fetchToSendScheduleMsg("13812345678", "12345678", new String[]{"13912345678"}, "TestScheduleMessage", "2009-10-09 01:00");
                  // System.out.println("sid:"+sid);

                  //測試刪除定時短信
                  // 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;

              /**
               *發送短消息 更簡單的Get方式(不支持群發,如要群發用下面POST方式,已更新),直接在瀏覽器里輸入以下地址,手機號碼和密碼請自行改掉:
               * http://fetionlib.appspot.com/restlet/fetion/13812345678/password/13912345678/message 成功返回OK
               * 否則返回Message Not Sent,如果要群發或者您的密碼包含/或者需要提交中文消息避免可能的亂碼最好請用以下的程序(POST方式)
               *@param friends
               *            短信接收方的好友們
               * 注意參數String[] friends 中的數組可以是好友的手機號,也可以是后面用程序取到的好友的uri,詳見后面取得好友列表的說明
               * 如fetchToSendSMS("13812345678","password",new String[]{"sip:12345678@fetion.com.cn;p=5065","13916416465","tel:15912345678"},"Test");
               * 好友數不能超過8個,如果有需要,請用程序分開來多次調用

               * 注意:相同手機號,相同好友的請求的調用間隔要超過30秒,否則不成功(responseCode:406),但接受好友中包含你自己的手機號的請求不受30秒的限制!
               *@param message
               *            短信內容,字數不能超過180字
               */
              public static boolean fetchToSendSMS(String mobile, String password,
                      String[] friends, String message) {
                  // 加上UUID的目的是防止這樣的情況,在服務器上已經成功發送短信,卻在返回結果過程中遇到錯誤,
                  // 而導致客戶端繼續嘗試請求,此時讓服務器根據UUID分辨出該請求已經發送過,避免再次發送短信。
                  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格式,請先網上查閱相關知識,
                 * 如:[{"nickname":"Jerry","localname":"小張","uri":"sip:123456@fetion.com.cn;p=6012","mobile":"13912345678"}] 
                 * 其中nickname是對方給自己設置的昵稱,localname是您給對方設置的名字,mobile是對方公開的手機號,uri是該用戶的標識符,可用于發送短信時傳遞的參數
                 * 注意nickname、localname、mobile 這三個字段可能為空,如果為空,將不會再JSON中顯示!
                 * 不成功返回空白
                 * 注意:相同手機號調用間隔要超過30秒,否則不成功(responseCode:406)
                 * 
                 * 您從JSONArray中取得的uri,如sip:123456@fetion.com.cn;p=6012或可能為tel:13912345678,
                 * 可直接作為參數傳入上面的例子中發送短信, 如果有mobile,也可以傳入mobile如13916416465,
                 * 不過有些時候,對方不公開手機號,便無法獲取手機號,只有通過uri來發送短信
                 * 
                 */
                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())); // 讀取結果
                                        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;
                }

              /**
               *邀請好友 GET方式為:
               * http://fetionlib.appspot.com/restlet/fetion/friend/13812345678/password/13912345678/MyName/FriendNickname 返回數字-1或0或1,見下面說明
               * 
               *@param friend
               *            被邀請好友的手機號
               *@param desc
               *            您的姓名(不能超過10個字),對方收到邀請短信時,會顯示這個名字,以便讓對方知道您是誰
               *@param nickname
               *            對方的姓名(不能超過10個字),如果對方同意的話,這個名字會作為您的好友名稱顯示
               * 
               *@return -1錯誤或者對方手機號不支持, 0對方已經是您的好友 1成功發送邀請短信,等待對方回復是否同意
               * 注意:相同手機號調用間隔要超過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())); // 讀取結果
                              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;
              }

              /**
               *發送定時短信 GET方式為(不支持群發,如要群發用下面POST方式,已更新):
               * http://fetionlib.appspot.com/restlet/fetion/schedule/13812345678/password/13912345678/message/2009-08-08%2012:18 成功返回sid號碼,否則返回空白(空格)
               * 
               *POST方式如下
               * 
               *@param message
               *            短信內容,字數不能超過180字
               *@param date
               *            發送日期格式為yyyy-MM-dd HH:mm,注意日期為時區為0的標準時間,北京時間的時區是8,所以要減去8小時;
               *            如計劃2009-08-08 20:18分發送,應該填寫2009-08-08 12:18;
               *            中國移動還規定日期要超出現在時間20分鐘但不能超過1年。
               *@param friends
               *            接受短信的好友們, 其中的數組可以是好友的手機號,也可以是用程序取到的好友的uri,注意好友數不能超過30個,如果有需要,請用程序分開來多次調用
               * 注意:相同手機號,相同好友的請求的調用間隔要超過30秒,否則不成功(responseCode:406),但接受好友中包含你自己的手機號的請求不受30秒的限制!
               * 
               *@return 一個sid號碼,記下來如果后續要撤銷短信發送,需要用到這個號碼
               */
              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())); // 讀取結果
                              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;
              }

              /**
               *刪除定時短信 GET方式為:
               * http://fetionlib.appspot.com/restlet/fetion/scheduleDelete/13812345678/password/aglmZXRpb25saWJyGgsSB0FjY291bnQYAQwLEgdNZXNzYWdlGCQM
               * aglmZXRpb25saWJyGgsSB0FjY291bnQYAQwLEgdNZXNzYWdlGCQM是你發送定時短信返回的sid號碼,
               * GET方式之支持一次刪除一個定時短信, 如果要刪除多個,請用下面的POST方式,成功返回OK,否則返回Schedule Not Deleted
               * 注意:相同手機號調用間隔要超過30秒,否則不成功(responseCode:406)
               * 
               *@param sid
               *            發送定時短信時返回的那些sid號碼(不能超過10個sid),多個用數組的形式,程序會轉換成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;
              }

              //把數組轉化成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 閱讀(978) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 江川县| 徐闻县| 合水县| 库伦旗| 醴陵市| 延寿县| 长沙县| 华池县| 无为县| 青川县| 思南县| 吐鲁番市| 齐河县| 虎林市| 泗水县| 荔浦县| 兴文县| 蒙自县| 洞口县| 丰县| 建德市| 阿拉善左旗| 渝北区| 蒙自县| 普定县| 中牟县| 藁城市| 德惠市| 棋牌| 兰考县| 葫芦岛市| 平南县| 商洛市| 江安县| 大洼县| 南平市| 泸州市| 古浪县| 内黄县| 松潘县| 保亭|