1、使用极光推送()向安卓手机推送消息【服务端向客户端主送推送】,C#语言
在VisualStudio2010中新建网站JPushAndroid。添加引用json帮助类库Newtonsoft.Json.dll。
在web.config增加appkey和mastersecret,可以在极光官网申请。web.config源码:
2、"b232c57153afc71ed74ae3da"/>
3、Collections.Generic; using System.Linq; using System.Web; using System.Net; using System.Text; using System.IO; using System.Configuration; using System.Collections; /* * 参考文档: 选择里面的:服务器端 API,Push-API-V3 * * 极光推送的网站的网址是: * 旧版本V2 * 最新版本V3 * * 其中服务端的接口以及示例代码都在这里: */
4、
/// 5、ary>
private readonly string MasterSecret = ConfigurationManager.AppSettings["MasterSecret"];
/// 6、eivedUrl = "
/// 7、由Platform(平台)、Audience(设备对象标识)、Notification(通知)、Message(自定义消息)、Options(推送可选项)组成
/// 8、 HttpWebResponse response = null;
try
{
myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.Method = method;
myReq.ContentType = "application/json";
if (!String.IsNullOrEmpty(auth))
{
myReq.Header 9、s.Add("Authorization", "Basic " + auth);
}
if (method == "POST")
{
byte[] bs = UTF8Encoding.UTF8.GetBytes(reqParams);
myReq.ContentLength = bs.Length;
using (Stream reqStream = myReq.GetRequestStream())
10、 {
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
}
}
response = (HttpWebResponse)myReq.GetResponse();
HttpStatusCode statusCode = response.StatusCode;
if (Equ 11、als(response.StatusCode, HttpStatusCode.OK))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
{
resultJson = reader.ReadToEnd();
try
12、{
object json = Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson);
}
catch
{
resultJson = string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": 10086}}}}", "响应的结果不是正确的jso 13、n格式");
}
}
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
HttpStatusCode errorCode = ((HttpWebResponse)ex.Response).StatusCode;
14、
string statusDescription = ((HttpWebResponse)ex.Response).StatusDescription;
using (StreamReader sr = new StreamReader(((HttpWebResponse)ex.Response).GetResponseStream(), System.Text.Encoding.UTF8))
{
resultJson = sr.ReadToEnd() 15、
//{"errcode":404,"errmsg":"request api doesn't exist"}
Dictionary 16、ntainsKey("errcode"))
{
errCode = dict["errcode"].ToString();
}
if (dict.ContainsKey("errmsg"))
{
errMsg = dict["errmsg"].ToString();
}
17、 resultJson = string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": {1}}}}}", errMsg, errCode);
}
}
else
{
//这里一定是error作为键名(自定义错误号10086),和极光推送失败时的json格式保持一致 如 {"error": {"message": "Missing parameter", "cod 18、e": 1002}}
resultJson = string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": 10086}}}}", ex.Message.Replace("\"", " ").Replace("'", " "));
}
}
catch (System.Exception ex)
{
resultJson = string.Format("{{\"error\": {{\"mes 19、sage\": \"{0}\", \"code\": 10086}}}}", ex.Message.Replace("\"", " ").Replace("'", " "));
}
finally
{
if (response != null)
{
response.Close();
}
if (myReq != null)
{
myReq.Ab 20、ort();
}
}
return resultJson;
}
/// 21、ding.Default.GetBytes(str);
return Convert.ToBase64String(bytes);
}
/// 22、Options(推送可选项)组成
/// 23、y>
/// 请求的json参数,一般由Platform(平台)、Audience(设备对象标识)、Notification(通知)、Message(自定义消息)、Options(推送可选项)组成
/// 24、 this.RequestUrl, auth, reqParams);
}
/// 25、ing reqParams)
{
string auth = GetBase64Auth();
return SendRequest("GET", this.RequestUrl, auth, reqParams);
}
/*
* 生成唯一的sendNo的方法: 取序列号
* 查看返回结果的方法
*/
/// 26、信息唯一id
/// 27、sendno":"123456","msg_id":"1799597405"}
* 或者 {"sendno":"0","msg_id":"351403900"}
* 2.入参json完全正确,但找不到要到达的设备。错误时:返回
* {"msg_id": 3125719446, "error": {"message": "cannot find user by this audience", "code": 1011}}
* 3.传入空字符串 或者 非json格式,或者没有必须的选项:{"error": {"message": "Missing 28、 parameter", "code": 1002}}
* 传入的键(键区分大小写)、值不符合要求 {"error": {"message": "Audience value must be JSON Array format!", "code": 1003}}
*/
/// 29、blic Hashtable JsonToHashtable(string jsonString)
{
/*
* 正确时返回结果{"sendno":"123456","msg_id":"1799597405"}
* {"sendno":"0","msg_id":"351403900"}
* 入参json完全正确,但找不到要到达的设备。错误时:返回 {"msg_id": 3125719446, "error": {"message": "cannot find user by this audience" 30、 "code": 1011}}
* 传入空字符串 或者 非json格式,或者没有必须的选项:{"error": {"message": "Missing parameter", "code": 1002}}
* 传入的键值不符合要求 {"error": {"message": "Audience value must be JSON Array format!", "code": 1003}} 键区分大小写
*/
Hashtable ht = new Hashtable();
object jso 31、n = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
//返回的结果一定是一个json对象
Newtonsoft.Json.Linq.JObject jsonObject = json as Newtonsoft.Json.Linq.JObject;
if (jsonObject == null)
{
return ht;
}
foreach (Newtonsoft.Json.Linq.J 32、Property jProperty in jsonObject.Properties())
{
Newtonsoft.Json.Linq.JToken jToken = jProperty.Value;
string value = "";
if (jToken != null)
{
value = jToken.ToString();
}
ht.Add(jProperty.Name, 33、 value);
}
return ht;
}
/// 34、c bool IsSuccess(string jsonString, out string errorMessage, out string errorCode)
{
Hashtable ht = JsonToHashtable(jsonString);
errorMessage = "";
errorCode = "";
foreach (string key in ht.Keys)
{
//如果存在error键,说明推送出错
if (k 35、ey == "error")
{
string errJson = ht[key].ToString();
Hashtable htError = JsonToHashtable(errJson);
errorMessage = htError["message"].ToString();
errorCode = htError["code"].ToString();
return false;
36、 }
}
return true;
}
/// 37、am name="errorCode">错误号
/// 用户自定义的推送编号(从序列号中获取),不设置则为0,成功后返回该编号
/// 极光服务器处理后返回的信息编号
/// 38、 out string msg_id)
{
bool result = IsSuccess(jsonString, out errorMessage, out errorCode);
Hashtable ht = JsonToHashtable(jsonString);
sendno = "";
msg_id = "";
if (result) //推送成功时,只有键sendno、msg_id
{
sendno = ht["sendno"].ToSt 39、ring();
msg_id = ht["msg_id"].ToString();
}
else //如果失败时存在msg_id键,则记录msg_id的值
{
if (ht.ContainsKey("msg_id"))
{
msg_id = ht["msg_id"].ToString();
}
}
return result;
}
/// 40、ummary>
/// 将返回的json转换为字典Dictionary对象
/// 41、 object json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
//返回的结果一定是一个json对象
Newtonsoft.Json.Linq.JObject jsonObject = json as Newtonsoft.Json.Linq.JObject;
if (jsonObject == null)
{
return ht;
}
foreach (Newtonsoft.J 42、son.Linq.JProperty jProperty in jsonObject.Properties())
{
Newtonsoft.Json.Linq.JToken jToken = jProperty.Value;
string value = "";
if (jToken != null)
{
value = jToken.ToString();
}
ht.Add(jPrope 43、rty.Name, value);
}
return ht;
}
}
☆JPushV2类代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography;
/*
* 44、参考文档: 选择里面的:服务器端 API,Push-API-V3
*
* 极光推送的网站的网址是:
* 旧版本V2
* 最新版本V3
*
* 其中服务端的接口以及示例代码都在这里:
*/
/// 45、 ///
46、开始推送方法 /// /// 设备号 RV1D41L5F1T public void PushAndroid(string RegistrationID) { try { Random ran = new Random(); int sendno = ran.Next(1, 2100000000);//随机生成的一个编号 string app_k
47、ey = AppKey; string masterSecret = APIMasterSecret; int receiver_type = 4;//接收者类型。2、指定的 tag。3、指定的 alias。4、广播:对 app_key 下的所有用户推送消息。5、根据 RegistrationID 进行推送。当前只是 Android SDK r1.6.0 版本支持 string receiver_value = RegistrationID; /* int msg_type = 1;//1、通知 2、自定义消息(只有 Android 支持) //通过json来推送消息内容。title-标题 content-推送的内容 string Title = "要推送的标题"; string Content = "要推送的内容"; string msg_content = "{\"n_builder_id\":\"00\",\"n_title\":\"" + Title + "\",\"n_content\":\"" + Content






