友盟推送
代码:
byte[] postData = Encoding.UTF8.GetBytes(postString);//编码,尤其是汉字,事先要看下抓取网页的编码方式 string url = "http://localhost/register.php";//地址 WebClient webClient = new WebClient(); webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可 byte[] responseData = webClient.UploadData(url, "POST", postData);//得到返回字符流 string srcString = Encoding.UTF8.GetString(responseData);
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { HttpWebRequest request = WebRequest.Create("http://www.baidu.com") as HttpWebRequest; Console.WriteLine("Begin " + DateTime.Now.ToString()); request.BeginGetResponse(new AsyncCallback(Compleate), request); Console.WriteLine("继续 " + DateTime.Now.ToString()); Console.Read(); } static void Compleate(IAsyncResult asyncResult) { Console.WriteLine("End " + DateTime.Now.ToString()); Console.WriteLine("异步完成"); if (asyncResult == null) { return; } HttpWebRequest req = (asyncResult.AsyncState as HttpWebRequest); HttpWebResponse res = req.EndGetResponse(asyncResult) as HttpWebResponse; StreamReader reader = new StreamReader(res.GetResponseStream()); Console.WriteLine(reader.ReadToEnd()); } } }
具体实现:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Newtonsoft.Json; using System.Configuration; using System.Net; using System.Net.Http; using System.Security.Cryptography; namespace Rongzi.BZone.Common.Util { public class UMengPush { private static readonly string UMengUrl = ConfigurationManager.AppSettings["UMengPush_Url"]; private static readonly string App_Key_Android = ConfigurationManager.AppSettings["App_Key_Android"]; private static readonly string App_Master_Secret_Android = ConfigurationManager.AppSettings["App_Master_Secret_Android"]; private static readonly string App_Key_IOS = ConfigurationManager.AppSettings["App_Key_IOS"]; private static readonly string App_Master_Secret_IOS = ConfigurationManager.AppSettings["App_Master_Secret_IOS"]; /// <summary> /// 安卓端广播 /// </summary> /// <param name="Ticker"></param> /// <param name="Title"></param> /// <param name="Text"></param> /// <returns></returns> public static bool PushBroadCast_Android(string Ticker, string Title, string Text) { try { PushRequest_Android req = new PushRequest_Android(); req.appkey = App_Key_Android; req.payload = new PayLoad_Android(); req.payload.display_type = DisplayType.notification.ToString(); req.payload.body = new Body(); req.payload.body.title = Title; req.payload.body.ticker = Ticker; req.payload.body.text = Text; req.payload.body.after_open = AfterOpen.go_app.ToString(); req.type = PushType.broadcast.ToString(); req.timestamp = GetTimeStamp(); string str = "POST" + UMengUrl + JsonConvert.SerializeObject(req) + App_Master_Secret_Android; string sign = GetMD5Hash(str); string url = UMengUrl + "?sign=" + sign; Send(url, JsonConvert.SerializeObject(req)); } catch (Exception ex) { LogHelper.Error(ex.Message); return false; } return true; } /// <summary> /// IOS端广播 /// </summary> /// <param name="Alert"></param> /// <returns></returns> public static bool PushBroadCast_IOS(string Alert) { try { PushRequest_IOS req = new PushRequest_IOS(); req.appkey = App_Key_IOS; req.payload = new PayLoad_IOS(); req.payload.aps = new APS(); req.payload.aps.Alert = Alert; req.timestamp = GetTimeStamp(); req.type = PushType.broadcast.ToString(); string str = "POST" + UMengUrl + JsonConvert.SerializeObject(req) + App_Master_Secret_IOS; string sign = GetMD5Hash(str); string url = UMengUrl + "?sign=" + sign; Send(url, JsonConvert.SerializeObject(req)); } catch (Exception ex) { LogHelper.Error(ex.Message); return false; } return true; } /// <summary> /// 安卓推送 /// </summary> /// <param name="Ticker">通知栏提示文字</param> /// <param name="Title">通知标题</param> /// <param name="Text">通知文字描述</param> /// <param name="DeviceTokens">设备唯一表示</param> /// <returns></returns> public static bool PushMessage_Android(string Ticker, string Title, string Text, List<string> DeviceTokens) { try { if (DeviceTokens.Count() == 0) { return true; } var PageSize = 500; var TotalCount = DeviceTokens.Count(); var TotalPages = TotalCount % PageSize == 0 ? TotalCount / PageSize : TotalCount / PageSize + 1; for (var i = 0; i < TotalPages; i++) { var list = DeviceTokens.Skip(i * PageSize).Take(PageSize).ToList<string>(); PushMessage_AndroidLimit(Ticker, Title, Text, list); } } catch (Exception ex) { LogHelper.Error(ex.Message); return false; } return true; } /// <summary> /// IOS推送(DeviceTokens不能超过500) /// </summary> /// <param name="Alert">通知文字描述</param> /// <param name="DeviceTokens">设备唯一表示</param> /// <returns></returns> public static bool PushMessage_IOS(string Alert, List<string> DeviceTokens) { try { if (DeviceTokens.Count() == 0) { return true; } var PageSize = 500; var TotalCount = DeviceTokens.Count(); var TotalPages = TotalCount % PageSize == 0 ? TotalCount / PageSize : TotalCount / PageSize + 1; for (var i = 0; i < TotalPages; i++) { var list = DeviceTokens.Skip(i * PageSize).Take(PageSize).ToList<string>(); PushMessage_IOSLimit(Alert, list); } } catch (Exception ex) { LogHelper.Error(ex.Message); return false; } return true; } /// <summary> /// 安卓推送(DeviceTokens不能超过500) /// </summary> /// <param name="Ticker">通知栏提示文字</param> /// <param name="Title">通知标题</param> /// <param name="Text">通知文字描述</param> /// <param name="DeviceTokens">设备唯一表示,要求不超过500个</param> /// <returns></returns> private static void PushMessage_AndroidLimit(string Ticker, string Title, string Text, List<string> DeviceTokens) { if (DeviceTokens.Count() == 0) { return; } PushRequest_Android req = new PushRequest_Android(); req.appkey = App_Key_Android; req.device_tokens = String.Join(",", DeviceTokens); req.payload = new PayLoad_Android(); req.payload.display_type = DisplayType.notification.ToString(); req.payload.body = new Body(); req.payload.body.title = Title; req.payload.body.ticker = Ticker; req.payload.body.text = Text; req.payload.body.after_open = AfterOpen.go_app.ToString(); req.type = PushType.listcast.ToString(); req.timestamp = GetTimeStamp(); string str = "POST" + UMengUrl + JsonConvert.SerializeObject(req) + App_Master_Secret_Android; string sign = GetMD5Hash(str); string url = UMengUrl + "?sign=" + sign; Send(url, JsonConvert.SerializeObject(req)); } /// <summary> /// IOS推送(DeviceTokens不能超过500) /// </summary> /// <param name="Alert">通知文字描述</param> /// <param name="DeviceTokens">设备唯一表示,要求不超过500个</param> private static void PushMessage_IOSLimit(string Alert, List<string> DeviceTokens) { if (DeviceTokens.Count() == 0) { return; } PushRequest_IOS req = new PushRequest_IOS(); req.appkey = App_Key_IOS; req.device_tokens = String.Join(",", DeviceTokens); req.payload = new PayLoad_IOS(); req.payload.aps = new APS(); req.payload.aps.Alert = Alert; req.timestamp = GetTimeStamp(); req.type = PushType.listcast.ToString(); string str = "POST" + UMengUrl + JsonConvert.SerializeObject(req) + App_Master_Secret_IOS; string sign = GetMD5Hash(str); string url = UMengUrl + "?sign=" + sign; Send(url, JsonConvert.SerializeObject(req)); } /// <summary> /// POST请求 /// </summary> /// <param name="url"></param> /// <param name="paras"></param> private static void Send(string url, string paras) { LogHelper.Info("推送地址:" + url); LogHelper.Info("推送请求体:" + paras); HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(url); //Post请求方式 request.Method = "POST"; byte[] bs = Encoding.UTF8.GetBytes(paras); request.ContentLength = bs.Length; using (Stream reqStream = request.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); reqStream.Close(); } request.BeginGetResponse(new AsyncCallback(Complete), request); } /// <summary> /// 异步返回 /// </summary> /// <param name="asyncResult"></param> private static void Complete(IAsyncResult asyncResult) { try { if (asyncResult == null) { return; } HttpWebRequest req = (asyncResult.AsyncState as HttpWebRequest); HttpWebResponse res = req.EndGetResponse(asyncResult) as HttpWebResponse; StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8); string result = reader.ReadToEnd(); LogHelper.Info("推送通知结果:" + result); reader.Close(); res.Close(); dynamic obj = JsonConvert.DeserializeObject(result); string ret = obj.ret; if (ret.ToUpper() != "SUCCESS") { LogHelper.Error(result); } //Result ret = JsonConvert.DeserializeObject(result) as Result; } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { Stream myResponseStream = ((HttpWebResponse)e.Response).GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string result = myStreamReader.ReadToEnd(); myStreamReader.Close(); dynamic obj = JsonConvert.DeserializeObject(result); string ret = obj.ret; if (ret.ToUpper() != "SUCCESS") { LogHelper.Error(result); } } } } /// <summary> /// 计算MD5 /// </summary> /// <param name="s"></param> /// <returns></returns> private static String GetMD5Hash(String str) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] result = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str)); StringBuilder strReturn = new StringBuilder(); for (int i = 0; i < result.Length; i++) { strReturn.Append(Convert.ToString(result[i], 16).PadLeft(2, '0')); } return strReturn.ToString().PadLeft(32, '0'); } /// <summary> /// 获取13位时间戳 /// </summary> /// <returns></returns> private static string GetTimeStamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds).ToString(); } } /// <summary> /// 消息类型 /// </summary> public enum DisplayType { /// <summary> /// 通知 /// </summary> notification, /// <summary> /// 消息 /// </summary> message } /// <summary> /// 点击"通知"的后续行为,默认为打开app。 /// </summary> public enum AfterOpen { /// <summary> /// 打开应用 /// </summary> go_app, /// <summary> /// 跳转到URL /// </summary> go_url, /// <summary> /// 打开特定的activity /// </summary> go_activity, /// <summary> /// 用户自定义内容 /// </summary> go_custom } /// <summary> /// 消息体 /// </summary> public class Body { /// <summary> /// 通知栏提示文字 /// </summary> public string ticker { get; set; } /// <summary> /// 通知标题 /// </summary> public string title { get; set; } /// <summary> /// 通知文字描述 /// </summary> public string text { get; set; } /// <summary> /// 点击"通知"的后续行为,默认为打开app /// </summary> public string after_open { get; set; } } /// <summary> /// 消息内容(Android最大为1840B), 包含参数说明如下(JSON格式) /// </summary> public class PayLoad_Android { /// <summary> /// 消息类型 /// </summary> public string display_type { get; set; } /// <summary> /// 消息体 /// </summary> public Body body { get; set; } } /// <summary> /// 消息发送类型 /// </summary> public enum PushType { /// <summary> /// 单播 /// </summary> unicast, /// <summary> /// 列播(要求不超过500个device_token) /// </summary> listcast, /// <summary> /// 文件播 /// </summary> filecast, /// <summary> /// 广播 /// </summary> broadcast, /// <summary> /// 组播 /// </summary> groupcast, /// <summary> /// 通过开发者自有的alias进行推送 /// </summary> customizedcast } /// <summary> /// Android推送请求体 /// </summary> public class PushRequest_Android { /// <summary> /// 应用唯一标识 /// </summary> public string appkey { get; set; } /// <summary> /// 时间戳,10位或者13位均可,时间戳有效期为10分钟 /// </summary> public string timestamp { get; set; } /// <summary> /// 消息发送类型 /// </summary> public string type { get; set; } /// <summary> /// 设备唯一表示 /// </summary> public string device_tokens { get; set; } /// <summary> /// 消息内容(Android最大为1840B), 包含参数说明如下(JSON格式) /// </summary> public PayLoad_Android payload { get; set; } } /// <summary> /// 严格按照APNs定义来填写 /// </summary> public class APS { public string Alert { get; set; } } /// <summary> /// 消息内容(iOS最大为2012B), 包含参数说明如下(JSON格式) /// </summary> public class PayLoad_IOS { public APS aps { get; set; } } /// <summary> /// IOS推送请求体 /// </summary> public class PushRequest_IOS { /// <summary> /// 应用唯一标识 /// </summary> public string appkey { get; set; } /// <summary> /// 时间戳,10位或者13位均可,时间戳有效期为10分钟 /// </summary> public string timestamp { get; set; } /// <summary> /// 消息发送类型 /// </summary> public string type { get; set; } /// <summary> /// 设备唯一表示 /// </summary> public string device_tokens { get; set; } /// <summary> /// 消息内容(iOS最大为2012B), 包含参数说明如下(JSON格式) /// </summary> public PayLoad_IOS payload { get; set; } } public class Message { public string msg_id { get; set; } // public string error_code { get; set; } } public class Result { public string ret { get; set; } public Message data { get; set; } } }
其他人异步请求:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; using System.Diagnostics; using Submail.AppConfig; using System.IO; using System.Net.Http.Headers; using Newtonsoft.Json.Linq; namespace Submail.Utility { public class HttpWebHelper { private const string APPID = "appid"; private const string TIMESTAMP = "timestamp"; private const string SIGN_TYPE = "sign_type"; private const string SIGNATURE = "signature"; private const string API_TIMESTAMP = "http://api.submail.cn/service/timestamp.json"; private IAppConfig _appConfig; public HttpWebHelper(IAppConfig appConfig) { this._appConfig = appConfig; } public string GetTimeStamp() { using (HttpClient httpClient = new HttpClient()) { using (HttpResponseMessage response = httpClient.GetAsync(API_TIMESTAMP).Result) { string jsonResult = response.Content.ReadAsStringAsync().Result; Dictionary<string, string> jsonMap = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonResult); if (jsonMap.ContainsKey(TIMESTAMP)) { return jsonMap[TIMESTAMP]; } } } return null; } public static bool CheckReturnJsonStatus(string retrunJsonResult) { Dictionary<string, string> jsonMap = JsonConvert.DeserializeObject<Dictionary<string, string>>(retrunJsonResult); if (jsonMap.ContainsKey("status") && jsonMap["status"].Equals("success", StringComparison.OrdinalIgnoreCase)) { return true; } return false; } public static bool CheckMultiReturnJsonStatus(string returnJsonResult) { JArray jarray = JArray.Parse(returnJsonResult); bool isAllSuccess = true; foreach (var item in jarray.Children()) { if (CheckReturnJsonStatus(item.ToString()) == false) { isAllSuccess = false; break; } } return isAllSuccess; } public string HttpPost(string httpUrl, Dictionary<string, object> dataPair) { using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add("charset", "UTF-8"); using (MultipartFormDataContent multipart = Build(dataPair)) { using (HttpResponseMessage response = httpClient.PostAsync(httpUrl, multipart).Result) { return response.Content.ReadAsStringAsync().Result; } } } } private MultipartFormDataContent Build(Dictionary<string, object> dataPair) { MultipartFormDataContent multipart = new MultipartFormDataContent(); string timeStamp = this.GetTimeStamp(); dataPair.Add(APPID, _appConfig.AppId); dataPair.Add(TIMESTAMP, timeStamp); dataPair.Add(SIGN_TYPE, _appConfig.SignType.ToString()); SignatureHelper sigHelper = new SignatureHelper(_appConfig); string formatData = RequestHelper.FormatRequest(dataPair); multipart.Add(new StringContent(sigHelper.GetSignature(formatData)), SIGNATURE); foreach (string key in dataPair.Keys) { string value = dataPair[key] as string; if (value != null) { multipart.Add(new StringContent(value), key); continue; } FileInfo file = dataPair[key] as FileInfo; if (file != null) { var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(file.FullName)); fileContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("multipart/form-data"); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { FileName = file.Name, Name = key, }; multipart.Add(fileContent); } } return multipart; } } }