星空网 > 软件开发 > ASP.net

信鸽推送 C#版SDK

  信鸽官方sdk没提供C#版的DEMO,考虑到应该有其他.NET的也会用到信鸽,下面是我在使用信鸽过程中写的demo。有什么不对的地方,欢迎各位大牛指导。
  使用过程中主要是有2个问题:
  1.参数组装,本demo使用Dictionary进行组装和排序;
  2.生成 sign(签名)

  下文贴出单个设备推送的代码(忽略大多数辅组实体的代码,下面会贴上源代码)
  1.Android 消息实体类 Message
  

  信鸽推送 C#版SDK信鸽推送 C#版SDK
public class Message{  public Message()  {    this.title = "";    this.content = "";    this.sendTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");    this.accept_time = new List<TimeInterval>();    this.multiPkg = 0;    this.raw = "";    this.loopInterval = -1;    this.loopTimes = -1;    this.action = new ClickAction();    this.style = new Style(0);    this.type = Message.TYPE_MESSAGE;  }  public bool isValid()  {    if (!string.IsNullOrWhiteSpace(raw))    {      return true;    }    if (type < TYPE_NOTIFICATION || type > TYPE_MESSAGE)      return false;    if (multiPkg < 0 || multiPkg > 1)      return false;    if (type == TYPE_NOTIFICATION)    {      if (!style.isValid()) return false;      if (!action.isValid()) return false;    }    if (expireTime < 0 || expireTime > 3 * 24 * 60 * 60)      return false;    try    {      DateTime.Parse(sendTime);    }    catch (Exception e)    {      return false;    }    foreach (var item in accept_time)    {      if (!item.isValid()) return false;    }    if (loopInterval > 0 && loopTimes > 0        && ((loopTimes - 1) * loopInterval + 1) > 15)    {      return false;    }    return true;  }  public string ToJosnByType()  {    if (type == TYPE_MESSAGE)    {      var obj = new { title = title, content = content, accept_time = accept_time.ToJson() };      return obj.ToJson();    }    return this.ToJson();  }  /// <summary>  /// 1:通知  /// </summary>  public static readonly int TYPE_NOTIFICATION = 1;  /// <summary>  /// 2:透传消息  /// </summary>  public static readonly int TYPE_MESSAGE = 2;  public String title;  public String content;  public int expireTime;  public String sendTime;  private List<TimeInterval> accept_time;  public int type;  public int multiPkg;  private Style style;  private ClickAction action;  /// <summary>  /// 自定义参数,所有的系统app操作参数放这里  /// </summary>  public string custom_content;  public String raw;  public int loopInterval;  public int loopTimes;}

View Code

  2.组装参数函数

  信鸽推送 C#版SDK信鸽推送 C#版SDK
/// <summary>/// Android单个设备 推送信息/// </summary>/// <param name="deviceToken">针对某一设备推送,token是设备的唯一识别 ID</param>/// <param name="message"></param>/// <returns></returns>public string pushSingleDevice(String deviceToken, Message message){  if (!ValidateMessageType(message))  {    return "";  }  if (!message.isValid())  {    return "";  }  Dictionary<String, Object> dic = new Dictionary<String, Object>();  dic.Add("access_id", this.m_accessId);  dic.Add("expire_time", message.expireTime);  dic.Add("send_time", message.sendTime);  dic.Add("multi_pkg", message.multiPkg);  dic.Add("device_token", deviceToken);  dic.Add("message_type", message.type);  dic.Add("message", message.ToJson());  dic.Add("timestamp", DateTime.Now.DateTimeToUTCTicks());  return CallRestful(XinGeAPIUrl.RESTAPI_PUSHSINGLEDEVICE, dic);}

View Code

  3.生成签名

  信鸽推送 C#版SDK信鸽推送 C#版SDK
/// <summary>/// 生成 sign(签名)/// </summary>/// <param name="method"></param>/// <param name="url"></param>/// <param name="dic"></param>/// <returns></returns>protected String GenerateSign(String method, String url, Dictionary<String, Object> dic){  var str = method;  Uri address = new Uri(url);  str += address.Host;  str += address.AbsolutePath;  var dic2 = dic.OrderBy(d => d.Key);  foreach (var item in dic2)  {    str += (item.Key + "=" + (item.Value == null ? "" : item.Value.ToString()));  }  str += this.m_secretKey;  var s_byte = Encoding.UTF8.GetBytes(str);  MD5 md5Hasher = MD5.Create();  byte[] data = md5Hasher.ComputeHash(s_byte);  StringBuilder sBuilder = new StringBuilder();  for (int i = 0; i < data.Length; i++)  {    sBuilder.Append(data[i].ToString("x2"));  }  return sBuilder.ToString();}

View Code

  4.生成请求的地址和调用请求

  信鸽推送 C#版SDK信鸽推送 C#版SDK
/// <summary>/// 生成请求的地址和调用请求/// </summary>/// <param name="url"></param>/// <param name="dic"></param>/// <returns></returns>protected string CallRestful(String url, Dictionary<String, Object> dic){  String sign = GenerateSign("POST", url, dic);  if (string.IsNullOrWhiteSpace(sign))  {    return (new { ret_code = -1, err_msg = "generateSign error" }).ToJson();  }  dic.Add("sign", sign);  try  {    var param = "";    foreach (var item in dic)    {      var key = item.Key;      var value = HttpUtility.UrlEncode(item.Value == null ? "" : item.Value.ToString(), Encoding.UTF8);      param = string.IsNullOrWhiteSpace(param) ? string.Format("{0}={1}", key, value) : string.Format("{0}&{1}={2}", param, key, value);    }    return Request(url, "POST", param);  }  catch (Exception e)  {    return e.Message;  }}

View Code

  5.辅助校验方法

  信鸽推送 C#版SDK信鸽推送 C#版SDK
protected bool ValidateMessageType(Message message){  if (this.m_accessId < XinGeAPIUrl.IOS_MIN_ID)    return true;  else    return false;}

View Code

  6.Http请求

  信鸽推送 C#版SDK信鸽推送 C#版SDK
public string Request(string _address, string method = "GET", string jsonData = null, int timeOut = 5){  string resultJson = string.Empty;  if (string.IsNullOrEmpty(_address))    return resultJson;  try  {    Uri address = new Uri(_address);    // 创建网络请求     HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;    //System.Net.ServicePointManager.DefaultConnectionLimit = 50;     // 构建Head    request.Method = method;    request.KeepAlive = false;    Encoding myEncoding = Encoding.GetEncoding("utf-8");    if (!string.IsNullOrWhiteSpace(jsonData))    {      byte[] bytes = Encoding.UTF8.GetBytes(jsonData);      using (Stream reqStream = request.GetRequestStream())      {        reqStream.Write(bytes, 0, bytes.Length);        reqStream.Close();      }    }    request.Timeout = timeOut * 1000;    request.ContentType = "application/x-www-form-urlencoded";    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)    {      StreamReader reader = new StreamReader(response.GetResponseStream());      string responseStr = reader.ReadToEnd();      if (responseStr != null && responseStr.Length > 0)      {        resultJson = responseStr;      }    }  }  catch (Exception ex)  {    resultJson = ex.Message;  }  return resultJson;}

View Code

  7.发送一个推送

  信鸽推送 C#版SDK信鸽推送 C#版SDK
public bool pushSingleDevice(String deviceToken, string account, string title, string content, Dictionary<string, object> custom, out string returnStr){  content = content.Replace("\r", "").Replace("\n", "");    Message android = new Message();  android.title = title;  android.content = content;  android.custom_content = custom.ToJson();  returnStr = pushSingleDevice(deviceToken, android);  return true;}

View Code

  源码下载

  注意:IOS需要区分开发和正式环境




原标题:信鸽推送 C#版SDK

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

产品图片不够决定Listing“出路”:https://www.ikjzd.com/articles/124889
爆料!美西货柜价格飙升至3000美元?大批量卖家货物下落不明:https://www.ikjzd.com/articles/124892
全球首家!京东物流中欧班列跨境电商物流专列始发!:https://www.ikjzd.com/articles/1249
卖家们必学的向客户宣布涨价技巧:https://www.ikjzd.com/articles/124916
玩爆亚马逊广告,学会这招就够啦!:https://www.ikjzd.com/articles/124917
新冠疫情下,中西部外贸逆势高增长,凭什么?:https://www.ikjzd.com/articles/124918
桂林酒店销售多少钱 桂林旅游宾馆价格:https://www.vstour.cn/a/410227.html
十里银滩旅游攻略玩什么住哪里怎么去?:https://www.vstour.cn/a/410228.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流