在VisualStudio2010中新建網站JPushAndroid。添加引用json幫助類庫Newtonsoft.Json.dll。 在web.config增長appkey和mastersecret,能夠在極光官網www.jpush.cn申請。web.config源碼: <?xml version="1.0"?> <!-- 有關如何配置 ASP.NET 應用程序的詳細信息,請訪問 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <appSettings> <add key="AppKey" value="b232c57153afc71ed74ae3da"/> <add key="MasterSecret" value="1ed5fcf68f44ea2a6b01e854"/> </appSettings> <system.web> <compilation debug="true" targetFramework="4.0"/> </system.web> </configuration> 添加類JPushV3,會彈出保存類在App_code文件夾下,肯定。 JpushV3代碼以下: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Net; using System.Text; using System.IO; using System.Configuration; using System.Collections; /* * 參考文檔:http://docs.jpush.cn/display/dev/Index 選擇裏面的:服務器端 API,Push-API-V3 * * 極光推送的網站的網址是:https://www.jpush.cn/ * 舊版本V2 http://docs.jpush.cn/display/dev/Push+API+v2 * 最新版本V3 http://docs.jpush.cn/display/dev/Push-API-v3 * * 其中服務端的接口以及示例代碼都在這裏:http://docs.jpush.cn/display/dev/Server-SDKs */ /// <summary> /// 極光推送的最新版:PUSH-API-V3 /// 參考地址 http://docs.jpush.cn/display/dev/Push-API-v3 /// POST https://api.jpush.cn/v3/push /// </summary> public class JPushV3 { /// <summary> /// 應用標識:極光推送的用戶名 /// </summary> private readonly string AppKey = ConfigurationManager.AppSettings["AppKey"]; /// <summary> /// 極光推送的密碼 /// </summary> private readonly string MasterSecret = ConfigurationManager.AppSettings["MasterSecret"]; /// <summary> /// 極光推送請求的url地址 /// </summary> private readonly string RequestUrl = "https://api.jpush.cn/v3/push"; /// <summary> /// 查詢推送結果請求的Url地址 /// </summary> private readonly string ReceivedUrl = "https://report.jpush.cn/v3/received"; /// <summary> /// 發送推送請求到JPush,使用HttpWebRequest /// </summary> /// <param name="method">傳入POST或GET</param> /// <param name="url">固定地址</param> /// <param name="auth">用戶名AppKey和密碼MasterSecret造成的Base64字符串</param> /// <param name="reqParams">請求的json參數,通常由Platform(平臺)、Audience(設備對象標識)、Notification(通知)、Message(自定義消息)、Options(推送可選項)組成</param> /// <returns></returns> public string SendRequest(String method, String url, String auth, String reqParams) { string resultJson = ""; HttpWebRequest myReq = null; HttpWebResponse response = null; try { myReq = (HttpWebRequest)WebRequest.Create(url); myReq.Method = method; myReq.ContentType = "application/json"; if (!String.IsNullOrEmpty(auth)) { myReq.Headers.Add("Authorization", "Basic " + auth); } if (method == "POST") { byte[] bs = UTF8Encoding.UTF8.GetBytes(reqParams); myReq.ContentLength = bs.Length; using (Stream reqStream = myReq.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); reqStream.Close(); } } response = (HttpWebResponse)myReq.GetResponse(); HttpStatusCode statusCode = response.StatusCode; if (Equals(response.StatusCode, HttpStatusCode.OK)) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8)) { resultJson = reader.ReadToEnd(); try { object json = Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson); } catch { resultJson = string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": 10086}}}}", "響應的結果不是正確的json格式"); } } } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { HttpStatusCode errorCode = ((HttpWebResponse)ex.Response).StatusCode; string statusDescription = ((HttpWebResponse)ex.Response).StatusDescription; using (StreamReader sr = new StreamReader(((HttpWebResponse)ex.Response).GetResponseStream(), System.Text.Encoding.UTF8)) { resultJson = sr.ReadToEnd(); //{"errcode":404,"errmsg":"request api doesn't exist"} Dictionary<string, object> dict = JsonToDictionary(resultJson); string errCode = "10086"; string errMsg = "發送推送的請求地址不存在或沒法鏈接"; if (dict.ContainsKey("errcode")) { errCode = dict["errcode"].ToString(); } if (dict.ContainsKey("errmsg")) { errMsg = dict["errmsg"].ToString(); } resultJson = string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": {1}}}}}", errMsg, errCode); } } else { //這裏必定是error做爲鍵名(自定義錯誤號10086),和極光推送失敗時的json格式保持一致 如 {"error": {"message": "Missing parameter", "code": 1002}} resultJson = string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": 10086}}}}", ex.Message.Replace("\"", " ").Replace("'", " ")); } } catch (System.Exception ex) { resultJson = string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": 10086}}}}", ex.Message.Replace("\"", " ").Replace("'", " ")); } finally { if (response != null) { response.Close(); } if (myReq != null) { myReq.Abort(); } } return resultJson; } /// <summary> /// 經過用戶名AppKey和密碼獲取驗證碼 /// </summary> /// <returns></returns> private string GetBase64Auth() { string str = this.AppKey + ":" + this.MasterSecret; byte[] bytes = Encoding.Default.GetBytes(str); return Convert.ToBase64String(bytes); } /// <summary> /// 發送推送請求到JPush /// </summary> /// <param name="method">POST或GET</param> /// <param name="reqParams">請求的json參數,通常由Platform(平臺)、Audience(設備對象標識)、Notification(通知)、Message(自定義消息)、Options(推送可選項)組成</param> /// <returns></returns> public string SendRequest(String method, String reqParams) { string auth = GetBase64Auth(); return SendRequest(method, this.RequestUrl, auth, reqParams); } /// <summary> /// 發送Post請求 /// </summary> /// <param name="reqParams">請求的json參數,通常由Platform(平臺)、Audience(設備對象標識)、Notification(通知)、Message(自定義消息)、Options(推送可選項)組成</param> /// <returns></returns> public string SendPostRequest(String reqParams) { string auth = GetBase64Auth(); return SendRequest("POST", this.RequestUrl, auth, reqParams); } /// <summary> /// 發送Get請求 /// </summary> /// <param name="reqParams">請求的json參數,通常由Platform(平臺)、Audience(設備對象標識)、Notification(通知)、Message(自定義消息)、Options(推送可選項)組成</param> /// <returns></returns> public string SendGetRequest(String reqParams) { string auth = GetBase64Auth(); return SendRequest("GET", this.RequestUrl, auth, reqParams); } /* * 生成惟一的sendNo的方法: 取序列號 * 查看返回結果的方法 */ /// <summary> /// 查詢推送的結果 /// </summary> /// <param name="msg_ids">生成的json信息惟一id</param> /// <returns></returns> public string GetReceivedResult(String msg_ids) { string url = this.ReceivedUrl + "?msg_ids=" + msg_ids; String auth = GetBase64Auth(); return SendRequest("GET", url, auth, null); ; } /* * 1.正確時返回結果{"sendno":"123456","msg_id":"1799597405"} * 或者 {"sendno":"0","msg_id":"351403900"} * 2.入參json徹底正確,但找不到要到達的設備。錯誤時:返回 * {"msg_id": 3125719446, "error": {"message": "cannot find user by this audience", "code": 1011}} * 3.傳入空字符串 或者 非json格式,或者沒有必須的選項:{"error": {"message": "Missing parameter", "code": 1002}} * 傳入的鍵(鍵區分大小寫)、值不符合要求 {"error": {"message": "Audience value must be JSON Array format!", "code": 1003}} */ /// <summary> /// 將返回的json轉換爲Hashtable對象 /// </summary> /// <param name="jsonString"></param> /// <returns></returns> public Hashtable JsonToHashtable(string jsonString) { /* * 正確時返回結果{"sendno":"123456","msg_id":"1799597405"} * {"sendno":"0","msg_id":"351403900"} * 入參json徹底正確,但找不到要到達的設備。錯誤時:返回 {"msg_id": 3125719446, "error": {"message": "cannot find user by this audience", "code": 1011}} * 傳入空字符串 或者 非json格式,或者沒有必須的選項:{"error": {"message": "Missing parameter", "code": 1002}} * 傳入的鍵值不符合要求 {"error": {"message": "Audience value must be JSON Array format!", "code": 1003}} 鍵區分大小寫 */ Hashtable ht = new Hashtable(); object json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString); //返回的結果必定是一個json對象 Newtonsoft.Json.Linq.JObject jsonObject = json as Newtonsoft.Json.Linq.JObject; if (jsonObject == null) { return ht; } foreach (Newtonsoft.Json.Linq.JProperty jProperty in jsonObject.Properties()) { Newtonsoft.Json.Linq.JToken jToken = jProperty.Value; string value = ""; if (jToken != null) { value = jToken.ToString(); } ht.Add(jProperty.Name, value); } return ht; } /// <summary> /// 根據json返回的結果判斷是否推送成功 /// </summary> /// <param name="jsonString">響應的json</param> /// <param name="errorMessage">錯誤信息</param> /// <param name="errorCode">錯誤號</param> /// <returns></returns> public bool IsSuccess(string jsonString, out string errorMessage, out string errorCode) { Hashtable ht = JsonToHashtable(jsonString); errorMessage = ""; errorCode = ""; foreach (string key in ht.Keys) { //若是存在error鍵,說明推送出錯 if (key == "error") { string errJson = ht[key].ToString(); Hashtable htError = JsonToHashtable(errJson); errorMessage = htError["message"].ToString(); errorCode = htError["code"].ToString(); return false; } } return true; } /// <summary> /// 根據返回的響應json來判斷推送是否成功,成功時記錄sendno與msg_id。 /// 失敗時記錄錯誤信息errorMessage、錯誤號errCode等 /// </summary> /// <param name="jsonString">響應的json</param> /// <param name="errorMessage">錯誤信息</param> /// <param name="errorCode">錯誤號</param> /// <param name="sendno">用戶自定義的推送編號(從序列號中獲取),不設置則爲0,成功後返回該編號</param> /// <param name="msg_id">極光服務器處理後返回的信息編號</param> /// <returns></returns> public bool IsSuccess(string jsonString, out string errorMessage, out string errorCode, out string sendno, out string msg_id) { bool result = IsSuccess(jsonString, out errorMessage, out errorCode); Hashtable ht = JsonToHashtable(jsonString); sendno = ""; msg_id = ""; if (result) //推送成功時,只有鍵sendno、msg_id { sendno = ht["sendno"].ToString(); msg_id = ht["msg_id"].ToString(); } else //若是失敗時存在msg_id鍵,則記錄msg_id的值 { if (ht.ContainsKey("msg_id")) { msg_id = ht["msg_id"].ToString(); } } return result; } /// <summary> /// 將返回的json轉換爲字典Dictionary對象 /// </summary> /// <param name="jsonString"></param> /// <returns></returns> public Dictionary<string, object> JsonToDictionary(string jsonString) { Dictionary<string, object> ht = new Dictionary<string, object>(); object json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString); //返回的結果必定是一個json對象 Newtonsoft.Json.Linq.JObject jsonObject = json as Newtonsoft.Json.Linq.JObject; if (jsonObject == null) { return ht; } foreach (Newtonsoft.Json.Linq.JProperty jProperty in jsonObject.Properties()) { Newtonsoft.Json.Linq.JToken jToken = jProperty.Value; string value = ""; if (jToken != null) { value = jToken.ToString(); } ht.Add(jProperty.Name, value); } return ht; } } ☆JPushV2類代碼 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Text; using System.Net; using System.IO; using System.Security.Cryptography; /* * 參考文檔:http://docs.jpush.cn/display/dev/Index 選擇裏面的:服務器端 API,Push-API-V3 * * 極光推送的網站的網址是:https://www.jpush.cn/ * 舊版本V2 http://docs.jpush.cn/display/dev/Push+API+v2 * 最新版本V3 http://docs.jpush.cn/display/dev/Push-API-v3 * * 其中服務端的接口以及示例代碼都在這裏:http://docs.jpush.cn/display/dev/Server-SDKs */ /// <summary> /// 這個版本是Push-API-v2版本,只能用到2015-12-31,建議直接使用最新版v3 /// post處理地址 http://api.jpush.cn:8800/v2/push /// </summary> public class JPushV2 { /// <summary> /// Android ApiKey /// </summary> private readonly string AppKey = ConfigurationManager.AppSettings["AppKey"]; /// <summary> /// Android密碼 /// </summary> private readonly string APIMasterSecret = ConfigurationManager.AppSettings["MasterSecret"]; /// <summary> /// Android極光推送:開始推送方法 /// </summary> /// <param name="RegistrationID">設備號 RV1D41L5F1T</param> public void PushAndroid(string RegistrationID) { try { Random ran = new Random(); int sendno = ran.Next(1, 2100000000);//隨機生成的一個編號 string app_key = AppKey; string masterSecret = APIMasterSecret; int receiver_type = 4;//接收者類型。二、指定的 tag。三、指定的 alias。四、廣播:對 app_key 下的全部用戶推送消息。五、根據 RegistrationID 進行推送。當前只是 Android SDK r1.6.0 版本支持 string receiver_value = RegistrationID; /* int msg_type = 1;//一、通知 二、自定義消息(只有 Android 支持) //經過json來推送消息內容。title-標題 content-推送的內容 string Title = "要推送的標題"; string Content = "要推送的內容"; string msg_content = "{\"n_builder_id\":\"00\",\"n_title\":\"" + Title + "\",\"n_content\":\"" + Content + "\"}";//消息內容 */ /* 當調用參數 msg_type = 1(通知) 時,msg_content JSON 要求: Key名稱 是否必須 Value內容說明 n_builder_id 可選 1-1000的數值,不填則默認爲 0,使用 極光Push SDK 的默認通知樣式。只有 Android 支持這個參數。 n_title 可選 通知標題。不填則默認使用該應用的名稱。只有 Android支持這個參數。 n_content 必須 通知內容。 n_extras 可選 通知附加參數。JSON格式。客戶端可取得所有內容。 */ int msg_type = 2;//一、通知 二、自定義消息(只有 Android 支持) //經過json來推送消息內容。title-標題 content-推送的內容 string msg_content = "{\"message\":\"xxxx12344554\"}";//消息內容 /* 當調用參數 msg_type = 2(自定義消息) 時,msg_content JSON 要求: Key名稱 是否必須 Value內容說明 message 必須 自定義消息的內容。 content_type 可選 message 字段裏的內容類型。用於特定的 message 內容解析 title 可選 消息標題 extras 可選 原樣返回,JSON 格式的更多的附屬信息 */ string platform = "android";//目標用戶終端手機的平臺類型,如: android, ios 多個請使用逗號分隔。 string verification_code = GetMD5Str(sendno.ToString(), receiver_type.ToString(), receiver_value, masterSecret);//驗證串,用於校驗發送的合法性。MD5 /* string postData = "sendno=" + sendno; postData += ("&app_key=" + app_key); postData += ("&masterSecret=" + masterSecret); postData += ("&receiver_type=" + receiver_type); postData += ("&receiver_value=" + receiver_value); postData += ("&msg_type=" + msg_type); postData += ("&msg_content=" + msg_content); postData += ("&platform=" + platform); postData += ("&verification_code=" + verification_code); */ string postData = "sendno=" + sendno; postData += ("&app_key=" + app_key); //postData += ("&masterSecret=" + masterSecret); postData += ("&receiver_type=" + receiver_type); postData += ("&receiver_value=" + receiver_value); postData += ("&verification_code=" + verification_code); postData += ("&msg_type=" + msg_type); postData += ("&msg_content=" + msg_content); postData += ("&platform=" + platform); //byte[] data = encoding.GetBytes(postData); byte[] data = Encoding.UTF8.GetBytes(postData); string resCode = GetPostRequest(data);//調用極光的接口獲取返回值 HttpContext.Current.Response.Write(resCode); JpushMsg msg = Newtonsoft.Json.JsonConvert.DeserializeObject<JpushMsg>(resCode);//定義一個JpushMsg類,包含返回值信息,將返回的json格式字符串轉成JpushMsg對象 /* 失敗json:{"sendno":"344076014","msg_id":2554996103,"errcode":1011,"errmsg":"cannot find user by this audience"} 成功json:{"sendno":"480383770","msg_id":"847350150","errcode":0,"errmsg":"Succeed"} * 發送自定義消息時:{"sendno":"1344179834","errcode":1003,"errmsg":"msg_content should be JSON format"} {"sendno":"151526149","msg_id":3635937751,"errcode":1003,"errmsg":"message should be in msg_content as a JSON key"} 參考地址:http://docs.jpush.cn/display/dev/Push-API-v3 * */ } catch (Exception ex) { HttpContext.Current.Response.Write(ex.Message); } } /// <summary> /// MD5加密驗證字符串,用於調用接口的時候,極光將作驗證使用 /// </summary> /// <param name="paras">參數數組</param> /// <returns>MD5字符串</returns> public string GetMD5Str(params string[] paras) { string str = ""; for (int i = 0; i < paras.Length; i++) { str += paras[i]; } byte[] buffer = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(str)); string md5Str = string.Empty; for (int i = 0; i < buffer.Length; i++) { md5Str = md5Str + buffer[i].ToString("X2"); } return md5Str; } /// <summary> /// Post方式請求獲取返回值 /// </summary> /// <param name="data"></param> /// <returns></returns> public string GetPostRequest(byte[] data) { HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://api.jpush.cn:8800/v2/push"); myRequest.Method = "POST";//極光http請求方式爲post myRequest.ContentType = "application/x-www-form-urlencoded";//按照極光的要求 myRequest.ContentLength = data.Length; Stream newStream = myRequest.GetRequestStream(); // Send the data. newStream.Write(data, 0, data.Length); newStream.Close(); // Get response var response = (HttpWebResponse)myRequest.GetResponse(); using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"))) { string result = reader.ReadToEnd(); reader.Close(); response.Close(); return result; } } } 類JpushMsg代碼: using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// 接收返回值信息 /// </summary> public class JpushMsg { private string sendno;//編號 public string Sendno { get { return sendno; } set { sendno = value; } } private string msg_id;//信息編號 public string Msg_id { get { return msg_id; } set { msg_id = value; } } private string errcode;//返回碼 public string Errcode { get { return errcode; } set { errcode = value; } } private string errmsg;//錯誤信息 public string Errmsg { get { return errmsg; } set { errmsg = value; } } } 新加web頁面Default.aspx 添加控件 V3-推送: <asp:Button ID="btnPushV3" Text="V3-推送" runat="server" onclick="btnPushV3_Click" /><br /> Default.aspx.cs按鈕事件代碼: protected void btnPushV3_Click(object sender, EventArgs e) { JPushV3 util = new JPushV3(); /*registration_id {"platform":"all","audience":"all","notification":{"alert":"Test from C# v3 sdk - alert-你好"},"options":{"apns_production":false}} */ //string reqParams = "{\"platform\":\"all\",\"audience\":\"all\",\"notification\":{\"alert\":\"Test from C# v3 sdk - alert-你好\"},\"options\":{\"apns_production\":false}}"; //string reqParams = "{\"platform\":[\"android\",\"ios\"],\"audience\":{\"tag\":[\"tag1\",\"tag2\"]},\"message\":{\"msg_content\":\"自定義消息測試:Test from C# v3 sdk - msgContent\",\"extras\":{\"from\":\"JPush\"}},\"options\":{\"apns_production\":false}}"; //string reqParams = "{\"platform\":[\"android\",\"ios\"],\"audience\":\"all\",\"message\":{\"msg_content\":\"自定義消息測試:Test from C# v3 sdk - msgContent\",\"title\":\"廣通測試標題\",\"extras\":{\"from\":\"JPush\"}},\"options\":{\"apns_production\":false}}"; string reqParams = "{\"platform\":[\"android\",\"ios\"],\"audience\":{\"alias\":[\"1899\"]},\"message\":{\"msg_content\":\"自定義消息測試:您有新的公文須要辦理\",\"title\":\"廣通測試標題註冊ID\",\"extras\":{\"from\":\"JPush\"}},\"options\":{\"sendno\":12345678}}"; //reqParams = "{\"platform\":[\"android\",\"ios\"],\"audience\":{\"alias\":[\"1001\"]},\"message\":{\"msg_content\":\"自定義消息測試:您有新的公文須要辦理\",\"title\":\"廣通測試標題註冊ID\",\"extras\":{\"from\":\"JPush\"}},\"options\":{\"apns_production\":false}}"; string jsonString = util.SendPostRequest(reqParams); Response.Write(jsonString + "<br />"); string errorMessage = ""; string errorCode = ""; string sendno = ""; string msg_id = ""; bool processResult = util.IsSuccess(jsonString, out errorMessage, out errorCode, out sendno, out msg_id); Response.Write("errorMessage:" + errorMessage + "<br />"); Response.Write("errorCode:" + errorCode + "<br />"); Response.Write("sendno:" + sendno + "<br />"); Response.Write("msg_id:" + msg_id + "<br />"); /*//遇到json的值中含有\"請使用\\\"來轉義 reqParams = "{\"platform\":[\"android\",\"ios\"],\"audience\":{\"alias\":[\"1001\"]},\"message\":{\"msg_content\":\"自定義消息測試:您有\\\"新的公文須要辦理\",\"title\":\"廣通測試標題註冊ID\",\"extras\":{\"from\":\"JPush\"}},\"options\":{\"apns_production\":false}}"; result = util.SendPostRequest(reqParams); Response.Write(result + "<br />");*/ //string result = util.GetReceivedResult("1799597405"); //Response.Write(result + "<br />"); /* * 正確時返回結果{"sendno":"123456","msg_id":"1799597405"} * {"sendno":"0","msg_id":"351403900"} * 入參json徹底正確,但找不到要到達的設備。錯誤時:返回 {"msg_id": 3125719446, "error": {"message": "cannot find user by this audience", "code": 1011}} * 傳入空字符串 或者 非json格式,或者沒有必須的選項:{"error": {"message": "Missing parameter", "code": 1002}} * 傳入的鍵值不符合要求 {"error": {"message": "Audience value must be JSON Array format!", "code": 1003}} 鍵區分大小寫 */ } 運行效果: