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

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

  

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 = ;
this.raw = "";
this.loopInterval = -;
this.loopTimes = -;
this.action = new ClickAction();
this.style = new Style();
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 < || multiPkg > )
return false;
if (type == TYPE_NOTIFICATION)
{
if (!style.isValid()) return false;
if (!action.isValid()) return false;
}
if (expireTime < || expireTime > * * * )
return false;
try
{
DateTime.Parse(sendTime);
}
catch (Exception e)
{
return false;
}
foreach (var item in accept_time)
{
if (!item.isValid()) return false;
}
if (loopInterval > && loopTimes >
&& ((loopTimes - ) * loopInterval + ) > )
{
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 = ;
/// <summary>
/// 2:透传消息
/// </summary>
public static readonly int TYPE_MESSAGE = ;
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;
}

  2.组装参数函数

  

/// <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);
}

  3.生成签名

  

/// <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 = ; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
}

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

  

/// <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 = -, 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;
}
}

  5.辅助校验方法

  

protected bool ValidateMessageType(Message message)
{
if (this.m_accessId < XinGeAPIUrl.IOS_MIN_ID)
return true;
else
return false;
}

  6.Http请求

  

public string Request(string _address, string method = "GET", string jsonData = null, int timeOut = )
{
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, , bytes.Length);
reqStream.Close();
}
}
request.Timeout = timeOut * ;
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 > )
{
resultJson = responseStr;
}
}
}
catch (Exception ex)
{
resultJson = ex.Message;
}
return resultJson;
}

  7.发送一个推送

  

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;
}

  源码下载

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

信鸽推送 C#版SDK的更多相关文章

  1. 信鸽推送 .NET (C#) 服务端 SDK rest api 调用库(v1.2)

    信鸽推送 .NET  服务端 SDK rest api 调用库-介绍 该版本是基于信鸽推送v2版本的时候封装的,先拿出来与大家分享,封装还还凑合,不依赖其他http调用件,唯一依赖json序列化dll ...

  2. 信鸽推送.NET SDK 开源

    github 地址 https://github.com/yeanzhi/XinGePushSDK.NET 传送门如何安装    建议使用nuget安装包,搜索"信鸽"即可    ...

  3. android app 集成 信鸽推送

    推送其实挺中意小米推送的,并经用户群占比还是比较大的,奈何拗不过php后端哥们的选型,就只好用信鸽推送了,期间接入过程中也是遇到不少问题,所以记录下来,以后如果还是用信鸽推送的话,估计看看以前的博客, ...

  4. 信鸽推送 10004,os文件配置出错,解决办法

    信鸽推送注册失败 返回码 10004 是 os  配置出现问题 经过询问客服,得到以下解决办法 将SDK中的so文件复制下来 新建文件夹jniLibs,并将 so 配置文件粘贴进去 便可完成注册

  5. QtAndroid具体解释(6):集成信鸽推送

    推送是我们开发移动应用经经常使用到的功能,Qt on Android 应用也会用到,之前也有朋友问过,这次我们来看看怎么在 Qt on Android 应用中来集成来自腾讯的信鸽推送. 有关信鸽的 S ...

  6. Android 信鸽推送通知栏不显示推送的通知

    使用信鸽推送,却怎么也没反应.经过查看log发现确实是收到了推送过来的消息了,其中有这么一行: W/dalvikvm(23255): VFY: unable to resolve virtual me ...

  7. QQ信鸽推送

    闲来无事,看看腾讯的信鸽推送! 优点: 1.毕竟大腿出的东西,不会太差 2.集成快 3.推送效率高,功能强,APP后台被杀的情况下同样能接受到推送. 废话少说,直接上代码: 源代码.zip

  8. iOS 关于信鸽推送点击推送通知的处理

    最近的项目中使用了推送模块,使用的是企鹅帝国的信鸽推送服务,关于具体怎么推送的,证书如何设置,我不再赘述,一来开发文档中已经讲的非常清楚,二来在网上一搜的话也能搜到一大堆:在这里主要写下关于推送的通知 ...

  9. 李洪强iOS之集成极光推送一iOS SDK概述

    李洪强iOS之集成极光推送一iOS SDK概述 JPush iOS 从上图可以看出,JPush iOS Push 包括 2 个部分,APNs 推送(代理),与 JPush 应用内消息. 红色部分是 A ...

随机推荐

  1. Selenium辅助工具

    下载Firefox39.0版本浏览器,安装firebug和FirePath.最新版的Firefox在扩展组件中无法找到firebug,可以使用旧的版本的Firefox浏览器. FirePath插件的使 ...

  2. 6w6:第六周程序填空题3

    描述 下面的程序输出结果是: A::Fun A::Do A::Fun C::Do 请填空: #include <iostream> using namespace std; class A ...

  3. windows如何通过端口查看对应程序

    今天打开SSR报错,说端口被占用. 打开的软件有点多,又不想重启.就需要找到占用的软件,关闭了即可. 打开cmd,输入netstat -aon能看到所有的使用端口 其中1080端口是预留给SSR使用的 ...

  4. 1. C/C++项目一

    需求: 使用C语言封装string 字符串,实现字符串的增.删.改.查等API函数. 要求: 不能使用 string 库函数,所有库函数必须自己手动实现. [项目实现] myString.h 代码如下 ...

  5. [HNOI2004]树的计数 BZOJ 1211 prufer序列

    题目描述 输入输出格式 输入格式: 输入文件第一行是一个正整数n,表示树有n个结点.第二行有n个数,第i个数表示di,即树的第i个结点的度数.其中1<=n<=150,输入数据保证满足条件的 ...

  6. elasticsearch head 连接不到elasticsearch

    配置好head后看到没有正常连接到elasticsearch.  重启后效果:

  7. [PowerShell]Quote in String

    今天遇到一个问题,如何在Select-String的Pattern参数里能使用双引号 比如 Select-String -path . -pattern "Lines: <span c ...

  8. JavaWeb学习笔记(三)—— Servlet

    一.Servlet概述 1.1 什么是Servlet Servlet是是sun公司提供一套规范(接口),是JavaWeb的三大组件之一(Servlet.Filter.Listener),它属于动态资源 ...

  9. class __init__()

    python 先定义函数才能调用 类是客观对象在人脑中的主观映射,生产对象的模板,类相当于盖房的图纸,生产工具的模具 模板 类:属性.方法 __init__() 这个方法一般用于初始化一个类但是 当实 ...

  10. Android HttpURLConnection的使用+Handler的原理及典型应用

    1.介绍 总结:HttpURLConnection用来发送和接收数据. 2.ANR异常报错 (1)ANR(Application not response) 应用无响应, 主线程(UI线程) (2)如 ...