C# 簡單的百度推送代碼

來源:互聯網
上載者:User

標籤:

前段時間搞推送來著,安卓方面用到了百度的推送服務,由於只是簡單的用到安卓推送的通知功能,所以沒用百度推薦的C# SDK,通過借鑒網上的各種資料和百度的API,費了老大勁終於折騰出來一段能用的代碼(早知道這麼糾結,直接用別人的了。。。強迫症傷不起啊)

/// <summary>    /// 百度推送    /// </summary>    public class BaiduPush    {        private const string method = "push_msg";        private const string url = "https://channel.api.duapp.com/rest/2.0/channel/channel";        private const string apikey = "xxxxxxxxxxxxxxxxx";        private const string secret_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";        public static string Push(string user_id, string title, string description, string msg_keys)        {            DateTime utcNow = DateTime.UtcNow;            DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0);            uint timestamp = (uint)(utcNow - epoch).TotalSeconds;            uint expires = (uint)(utcNow.AddDays(1) - epoch).TotalSeconds; //一天后到期            Dictionary<string, string> dic = new Dictionary<string, string>();            dic.Add("method", method);            dic.Add("apikey", apikey);            dic.Add("timestamp", timestamp.ToString());            dic.Add("expires", expires.ToString());            dic.Add("push_type", "1"); //單播            dic.Add("device_type", "3"); //Andriod裝置             dic.Add("user_id", user_id);            dic.Add("message_type", "1"); //只發通知            dic.Add("messages", "{\"title\":\"" + title + "\",\"description\":\"" + description + "\"}");            dic.Add("msg_keys", msg_keys); //訊息標識 相同訊息標識的訊息會自動覆蓋。只支援android。            dic.Add("sign", StructSign("POST", url, dic, secret_key));            StringBuilder sb = new StringBuilder();            foreach (var d in dic)            {                sb.Append(d.Key + "=" + d.Value + "&");            }            sb.Remove(sb.Length - 1, 1);            byte[] data = Encoding.UTF8.GetBytes(sb.ToString());            WebClient webClient = new WebClient();            try            {                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//採取POST方式必須加的header,如果改為GET方式的話就去掉這句話即可                  byte[] response = webClient.UploadData(url, "POST", data);                return Encoding.UTF8.GetString(response);            }            catch (WebException ex)            {                Stream stream = ex.Response.GetResponseStream();                byte[] bs = new byte[256];                int i = 0;                int b;                while ((b = stream.ReadByte()) > 0)                {                    bs[i++] = (byte)b;                }                stream.Close();                return Encoding.UTF8.GetString(bs, 0, i);            }        }        /// <summary>        /// 構建Sign        /// </summary>        /// <param name="httpMethod"></param>        /// <param name="url"></param>        /// <param name="dic"></param>        /// <param name="secret_key"></param>        /// <returns></returns>        private static string StructSign(string httpMethod, string url, Dictionary<string, string> dic, string secret_key)        {            //按key正序            dic = dic.OrderBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value);            StringBuilder sb = new StringBuilder();            //構建索引值對            foreach (var d in dic)            {                sb.Append(d.Key + "=" + d.Value);            }            string sign = httpMethod + url + sb + secret_key;            //url編碼            sign = sign.UrlEncode();            //將編碼後替換的字元大寫,這地方是個坑。。。            char[] cs = new char[sign.Length];            for (int i = 0; i < sign.Length; i++)            {                cs[i] = sign[i];                if (sign[i] == ‘%‘)                {                    cs[++i] = Convert.ToChar(sign[i].ToString().ToUpper());                    cs[++i] = Convert.ToChar(sign[i].ToString().ToUpper());                }            }            //MD5加密            return new string(cs).MD5();        }    }

外加兩個擴充方法  

System.Web.HttpUtility.UrlEncode需要添加引用System.Web (.net framework 4.0 client profile下面找不到System.Web請切換到.net framework 4.0)

/// <summary>        /// MD5加密        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static string MD5(this string str)        {            byte[] bs = new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(str));            return BitConverter.ToString(bs).Replace("-", "");        }        /// <summary>        /// url編碼        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static string UrlEncode(this string str)        {            return System.Web.HttpUtility.UrlEncode(str, Encoding.UTF8);        }

 

C# 簡單的百度推送代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.