百度云推送消息到手机

百度云推送消息,参考百度云推送官网,以下是核心代码:
private void SendNotificationToAndroid(string message)
        {

            BaiduPush Bpush = new BaiduPush("POST", SecretKey);
          
            String messages = "";
            String method = "push_msg";
            TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
            uint device_type = 3;//终端设备类型 3:Android  4:IOS
            uint unixTime = (uint)ts.TotalSeconds;

            uint message_type;//推送类型 0:透传消息 1:Notification
            string messageksy = "xxxxxx";
            message_type = 1;
            BaiduPushNotification notification = new BaiduPushNotification();
            notification.title = "报警信息";// TBTitle.Text;//标题
            notification.description = message;// TBDescription.Text;//消息内容
            messages = notification.getJsonString();
            PushOptions pOpts;
            pOpts = new PushOptions(method, AppKey, device_type, messages, messageksy, unixTime);//所有人
            pOpts.message_type = message_type;
            pOpts.deploy_status = 2;   //1;开发状态  2:生产状态

            string response = Bpush.PushMessage(pOpts);
            
        }

BaiduPushNitification.cs


public class BaiduPushNotification
    {
        public string title { get; set; } //通知标题,可以为空;如果为空则设为appid对应的应用名;
        public string description { get; set; } //通知文本内容,不能为空;
        public int notification_builder_id { get; set; } //android客户端自定义通知样式,如果没有设置默认为0;
        public int notification_basic_style { get; set; } //只有notification_builder_id为0时才有效,才需要设置,如果notification_builder_id为0则可以设置通知的基本样式包括(响铃:0x04;振动:0x02;可清除:0x01;),这是一个flag整形,每一位代表一种样式;
        public int open_type { get; set; }//点击通知后的行为(打开Url:1; 自定义行为:2:其它值则默认打开应用;);
        public string url { get; set; } //只有open_type为1时才有效,才需要设置,如果open_type为1则可以设置需要打开的Url地址;
        public int user_confirm { get; set; } //只有open_type为1时才有效,才需要设置,(需要请求用户授权:1;默认直接打开:0), 如果open_type为1则可以设置打开的Url地址时是否请求用户授权;
        public string pkg_content { get; set; }//只有open_type为2时才有效,才需要设置, 如果open_type为2则可以设置自定义打开行为(具体参考管理控制台文档);
        public string custom_content { get; set; }// 自定义内容,键值对,Json对象形式(可选);在android客户端,这些键值对将以Intent中的extra进行传递。

        public BaiduPushNotification()
        {
            notification_builder_id = 1;
            notification_basic_style = 0;

            url = "";
            user_confirm = 0;
            pkg_content = "";
            custom_content = "";
            open_type = 0;

        }

        public string getJsonString()
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(this);
        }
    }

BaiduPush.cs

public class BaiduPush
    {
        public PushOptions opts { get; set; }

        public string httpMehtod { get; set; }
        public string url { get; set; }
        public string secret_key { get; set; }

        public BaiduPush(string httpMehtod, string secret_key)
        {
            this.httpMehtod = httpMehtod;
            this.url = "http://channel.api.duapp.com/rest/2.0/channel/channel";
            this.secret_key = secret_key;
        }


        public string PushMessage(PushOptions opts)
        {

            this.opts = opts;

            Dictionary<string, string> dic = new Dictionary<string, string>();

            //将键值对按照key的升级排列
            var props = typeof(PushOptions).GetProperties().OrderBy(p => p.Name);
            foreach (var p in props)
            {
                if (p.GetValue(this.opts, null) != null)
                {
                    dic.Add(p.Name, p.GetValue(this.opts, null).ToString());
                }
            }
            //生成sign时,不能包含sign标签,所有移除
            dic.Remove("sign");

            var preData = new StringBuilder();
            foreach (var l in dic)
            {
                preData.Append(l.Key);
                preData.Append("=");
                preData.Append(l.Value);

            }

            //按要求拼接字符串,并urlencode编码
            var str = HttpUtility.UrlEncode(this.httpMehtod.ToUpper() + this.url + preData.ToString() + this.secret_key, System.Text.Encoding.UTF8);

            var strSignUpper = new StringBuilder();
            int perIndex = 0;
            for (int i = 0; i < str.Length; i++)
            {
                var c = str[i].ToString();
                if (str[i] == '%')
                {
                    perIndex = i;
                }
                if (i - perIndex == 1 || i - perIndex == 2)
                {
                    c = c.ToUpper();
                }
                strSignUpper.Append(c);
            }

            strSignUpper = strSignUpper.Replace("(", "%28").Replace(")", "%29");


            var sign = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strSignUpper.ToString(), "MD5").ToLower();

            //加入生成好的sign键值对
            dic.Add("sign", sign);
            var strb = new StringBuilder();
            //int tagIndex = 0;
            foreach (var l in dic)
            {

                strb.Append(l.Key);
                strb.Append("=");
                strb.Append(l.Value);
                strb.Append("&");
            }

            var postStr = strb.ToString().EndsWith("&") ? strb.ToString().Remove(strb.ToString().LastIndexOf('&')) : strb.ToString();


            byte[] data = Encoding.UTF8.GetBytes(postStr);//编码,尤其是汉字,事先要看下抓取网页的编码方式  
            WebClient webClient = new WebClient();
            try
            {
                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可  
                byte[] responseData = webClient.UploadData(this.url, "POST", data);//得到返回字符流  
                string srcString = Encoding.UTF8.GetString(responseData);//解码  
                return "Post:" + postStr + "\r\n\r\n" + "Response:" + srcString;
            }
            catch (WebException ex)
            {
                Stream stream = ex.Response.GetResponseStream();
                string m = ex.Response.Headers.ToString();
                byte[] buf = new byte[256];
                stream.Read(buf, 0, 256);
                stream.Close();
                int count = 0;
                foreach (var b in buf)
                {
                    if (b > 0)
                    {
                        count++;
                    }
                    else
                    {
                        break;
                    }
                }
                return " Post:" + postStr + ex.Message + "\r\n\r\n" + Encoding.UTF8.GetString(buf, 0, count);
            }
        }
    }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值