c# 服务端接入个推指定对象消息推送
个推消息推送主要步骤:1.获取鉴权token 2.发送推送消息 1.获取鉴权token(会过期,需要间隔时间获取一次): tokenUrl = "https://restapi.getui.com/v2/" + appId + "/auth"; private string GetToken() { long nowTime ; //当前的时间戳 毫秒级 string sign = appKey + nowTime + masterSecret; string sha256Sign = SHA256EncryptString(sign); //用sha256加密 string postParam = "{\"sign\":\"" + sha256Sign + "\",\"timestamp\":\"" + nowTime + "\",\"appkey\":\""+ appKey + "\"}"; //json格式的post参数 appkey masterSecret appid 申请应用后会有 return HttpRequestPost(tokenUrl, postParam); } private string HttpRequestPost(string Url, string Param) { string result = string.Empty; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Timeout = Timeout; request.ContentType = "application/json;charset=utf-8"; request.ReadWriteTimeout = Timeout; request.Proxy = null; request.ServicePoint.Expect100Continue = false; request.KeepAlive = false; request.ServicePoint.ConnectionLimit = 1000; //对象最大连接数 request.Method = "POST"; byte[] data = Encoding.UTF8.GetBytes(Param); using (Stream requestStream = request.GetRequestStream()) { using (StreamWriter swrite = new StreamWriter(requestStream)) { swrite.Write(data); } } HttpWebResponse wbResponse = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = wbResponse.GetResponseStream()) { using (StreamReader sread = new StreamReader(responseStream)) { result = sread.ReadToEnd(); } } } catch (Exception ex) { Console.WriteLine("GeTuiMsgTask.HttpRequestPost post failed url={0} ex={1}", Url, ex); } return result; } private string SHA256EncryptString(string data) { byte[] bytes = Encoding.UTF8.GetBytes(data); byte[] hash = SHA256Managed.Create().ComputeHash(bytes); StringBuilder builder = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { builder.Append(hash[i].ToString("x2")); } return builder.ToString(); } 2. 发送推送消息:必要参数 string cid 客户端给过来的clientid(目标用户) string requestId 请求唯一标识号,10-32位之间;如果request_id重复,会导致消息丢失 string title, 推送消息标题 string content 推送内容
pushUrl = "https://restapi.getui.com/v2/" + appId + "/push/single/cid"; 推送url
private void SendMsgNotification(object o) { MsgTaskItem item = (MsgTaskItem)o; string postParam = "{\"request_id\":\"" + item.RequestId + "\",\"audience\":{\"cid\":[\"" + item.Cid + "\"]}," + "\"push_message\":{\"notification\":{\"title\":\"" + item.Title + "\",\"body\":\"" + item.Content + "\",\"click_type\":\"none\",\"url\":\"\"}}}"; string result = HttpRequestPost(pushUrl, postParam); //返回结果成功也是json格式字符串 } 更具体的查看官方文档:https://docs.getui.com/getui/server/rest_v2/push/
在线http接口测试网站:https://www.sojson.com/http/test.html