码迷,mamicode.com
首页 > Windows程序 > 详细

C# 简单的百度推送代码

时间:2015-05-04 17:08:30      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

前段时间搞推送来着,安卓方面用到了百度的推送服务,由于只是简单的用到安卓推送的通知功能,所以没用百度推荐的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# 简单的百度推送代码

标签:

原文地址:http://www.cnblogs.com/luludongxu/p/4476318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!