Courier push C # SDK,
The official sdk does not provide a C # DEMO. Considering other. NET sdks, the following is a demo I wrote when I used it. What's wrong? Thank you for your guidance.
There are two main problems during use:
1. Parameter Assembly. This demo uses Dictionary for assembly and sorting;
2. Generate sign (Signature)
The Code pushed by a single device is pasted below (the code for ignoring most of the entity in the auxiliary group is pasted below)
1. Android Message entity 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 = 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: Notification // </summary> public static readonly int TYPE_NOTIFICATION = 1; /// <summary> /// 2: passthrough message // </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> /// custom parameter. Put all system app operation parameters here /// </summary> public string custom_content; public String raw; public int loopInterval; public int loopTimes ;}View Code
2. Assemble parameter functions
/// <Summary> /// push information for a single Android device /// </summary> /// <param name = "deviceToken"> push for a specific device, token is the unique identification ID of a device </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. Generate a signature
/// <Summary> /// generate sign (Signature) /// </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. Generate the request address and call request
/// <Summary> // generate the request address and call request // </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. Auxiliary verification methods
Protected bool ValidateMessageType (Message message) {if (this. m_accessId <XinGeAPIUrl. IOS_MIN_ID) return true; else return false ;}View Code
6. Http request
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); // create a network request HttpWebRequest request = WebRequest. create (address) as HttpWebRequest; // System. net. servicePointManager. defaultConnectionLimit = 50; // build a 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. Send a push
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
Source code download
Note: IOS requires differentiated development and formal environment