C#—ASP.NET:集成极光推送(Push API v3)
原文地址: https://blog.csdn.net/CXLLLK/article/details/86489994
1、极光推送官网(https://www.jpush.cn/)申请一个账号。
2、服务中心,开发者服务中,创建一个新的应用,输入正确的Android的包名
3、获取到了一个AppKey 和一个 Master Secret,这两个参数比较重要,验证权限使用。
4、去官网找到下载C# SDK的包https://docs.jiguang.cn/jpush/resources/
Github 源码:https://github.com/jpush/jpush-api-csharp-client
5、源码生成DLL
6、项目引用DLL,新建类 using Jiguang.JPush.Model;
7、代码封装HTTP 调用官方API,转载地址为pohreb博客:https://www.cnblogs.com/yangwujun/p/5973120.html
-
-
-
-
-
private const string AppKey = "填写你应用的AppKey";
-
-
-
-
private const string MasterSecret = "填写你的MasterSecret";
-
-
-
-
private const string RequestUrl = "https://api.jpush.cn/v3/push";
-
-
-
-
-
private const string ReceivedUrl = "https://report.jpush.cn/v3/received";
-
-
-
-
-
-
-
-
-
private static string SendRequest(String method, String url, String auth, String reqParams)
-
-
-
HttpWebRequest myReq = null;
-
HttpWebResponse response = null;
-
-
-
myReq = (HttpWebRequest)WebRequest.Create(url);
-
-
myReq.ContentType = "application/json";
-
if (!String.IsNullOrEmpty(auth))
-
-
myReq.Headers.Add("Authorization", "Basic " + auth);
-
-
-
-
byte[] bs = UTF8Encoding.UTF8.GetBytes(reqParams);
-
myReq.ContentLength = bs.Length;
-
using (Stream reqStream = myReq.GetRequestStream())
-
-
reqStream.Write(bs, 0, bs.Length);
-
-
-
-
response = (HttpWebResponse)myReq.GetResponse();
-
HttpStatusCode statusCode = response.StatusCode;
-
if (Equals(response.StatusCode, HttpStatusCode.OK))
-
-
using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
-
-
resultJson = reader.ReadToEnd();
-
-
-
object json = Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson);
-
-
-
-
resultJson = string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": 10086}}}}", "响应的结果不是正确的json格式");
-
-
-
-
-
-
-
if (ex.Status == WebExceptionStatus.ProtocolError)
-
-
HttpStatusCode errorCode = ((HttpWebResponse)ex.Response).StatusCode;
-
string statusDescription = ((HttpWebResponse)ex.Response).StatusDescription;
-
using (StreamReader sr = new StreamReader(((HttpWebResponse)ex.Response).GetResponseStream(), System.Text.Encoding.UTF8))
-
-
resultJson = sr.ReadToEnd();
-
-
Dictionary<string, object> dict = JsonToDictionary(resultJson);
-
string errCode = "10086";
-
string errMsg = "发送推送的请求地址不存在或无法连接";
-
if (dict.ContainsKey("errcode"))
-
-
errCode = dict["errcode"].ToString();
-
-
if (dict.ContainsKey("errmsg"))
-
-
errMsg = dict["errmsg"].ToString();
-
-
resultJson = string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": {1}}}}}", errMsg, errCode);
-
-
-
-
-
-
resultJson = string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": 10086}}}}", ex.Message.Replace("\"", " ").Replace("'", " "));
-
-
-
catch (System.Exception ex)
-
-
resultJson = string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": 10086}}}}", ex.Message.Replace("\"", " ").Replace("'", " "));
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
private static string GetBase64Auth()
-
-
string str = AppKey + ":" + MasterSecret;
-
byte[] bytes = Encoding.Default.GetBytes(str);
-
return Convert.ToBase64String(bytes);
-
-
-
-
-
-
-
-
public static string SendRequest(String method, String reqParams)
-
-
string auth = GetBase64Auth();
-
return SendRequest(method, RequestUrl, auth, reqParams);
-
-
-
-
-
-
-
public static string SendPostRequest(String reqParams)
-
-
string auth = GetBase64Auth();
-
return SendRequest("POST", RequestUrl, auth, reqParams);
-
-
-
-
-
-
-
public static string SendGetRequest(String reqParams)
-
-
string auth = GetBase64Auth();
-
return SendRequest("GET", RequestUrl, auth, reqParams);
-
-
-
-
-
-
-
-
-
-
-
public static string GetReceivedResult(String msg_ids)
-
-
string url = ReceivedUrl + "?msg_ids=" + msg_ids;
-
String auth = GetBase64Auth();
-
return SendRequest("GET", url, auth, null);
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
public static Hashtable JsonToHashtable(string jsonString)
-
-
-
-
-
-
-
-
-
Hashtable ht = new Hashtable();
-
object json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
-
-
Newtonsoft.Json.Linq.JObject jsonObject = json as Newtonsoft.Json.Linq.JObject;
-
-
-
-
-
foreach (Newtonsoft.Json.Linq.JProperty jProperty in jsonObject.Properties())
-
-
Newtonsoft.Json.Linq.JToken jToken = jProperty.Value;
-
-
-
-
value = jToken.ToString();
-
-
ht.Add(jProperty.Name, value);
-
-
-
-
-
-
-
-
-
-
-
public static bool IsSuccess(string jsonString, out string errorMessage, out string errorCode)
-
-
Hashtable ht = JsonToHashtable(jsonString);
-
-
-
foreach (string key in ht.Keys)
-
-
-
-
-
string errJson = ht[key].ToString();
-
Hashtable htError = JsonToHashtable(errJson);
-
errorMessage = htError["message"].ToString();
-
errorCode = htError["code"].ToString();
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
public static bool IsSuccess(string jsonString, out string errorMessage, out string errorCode, out string sendno, out string msg_id)
-
-
bool result = IsSuccess(jsonString, out errorMessage, out errorCode);
-
Hashtable ht = JsonToHashtable(jsonString);
-
-
-
-
-
sendno = ht["sendno"].ToString();
-
msg_id = ht["msg_id"].ToString();
-
-
-
-
if (ht.ContainsKey("msg_id"))
-
-
msg_id = ht["msg_id"].ToString();
-
-
-
-
-
-
-
-
-
-
public static Dictionary<string, object> JsonToDictionary(string jsonString)
-
-
Dictionary<string, object> ht = new Dictionary<string, object>();
-
object json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
-
-
Newtonsoft.Json.Linq.JObject jsonObject = json as Newtonsoft.Json.Linq.JObject;
-
-
-
-
-
foreach (Newtonsoft.Json.Linq.JProperty jProperty in jsonObject.Properties())
-
-
Newtonsoft.Json.Linq.JToken jToken = jProperty.Value;
-
-
-
-
value = jToken.ToString();
-
-
ht.Add(jProperty.Name, value);
-
-
-
-
8、其中我们主要使用registration_id的方式推送,也就是通过APP上的用户Token推送。
新增两个实体类一个存储APP用户Token,以及设备平台(安卓,苹果),一个存储推送记录,其实极光官网也有推送记录。
因为需要推送多个用户情况,新添List存储registration_id
新建返回对象存储返回信息
扩展方法使用,根据文档实现JSON格式并调用基本方法实现推送https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/
-
-
-
-
-
-
-
-
-
-
-
-
public static bool SendPushV2(List<string> RegistrationIDList, string title, string senduser, string toid,int contype,string dataid, string strMsg, bool is_production, out string strLog)
-
-
-
-
var parmARR = new Dictionary<string, object>();
-
parmARR.Add("dataid", dataid);
-
var mm = new M_PushRegistration();
-
mm.registration_id = RegistrationIDList;
-
-
PushPayload pushPayload = new PushPayload()
-
-
Platform = new List<string> { "android", "ios" },
-
-
Notification = new Notification
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
var strParms = pushPayload.Exp_ModelToJson();
-
strParms.WriteFile("log/push");
-
var result = JPushHelperV3.SendPostRequest(strParms);
-
var retM = result.Exp_JsonToModel<M_PushReturn>(1);
-
-
strLog += "result=" + result + "&&retModel=" + retM.Exp_ModelToJson();
-
strLog.WriteFile("log/push");
-
-
-
-
string[] teacherArr = toid.Split(',');
-
for (int i = 0; i < teacherArr.Length; i++)
-
-
D_T_PushMsg_Exp pushmsgDal = new D_T_PushMsg_Exp();
-
M_T_PushMsg pushmsgModel = new M_T_PushMsg();
-
pushmsgModel.Title = title;
-
pushmsgModel.MsgAuthor = senduser;
-
pushmsgModel.MsgContent = strMsg;
-
pushmsgModel.Flag = true;
-
pushmsgModel.IsRead = false;
-
pushmsgModel.IsSend = true;
-
pushmsgModel.Contype = contype;
-
pushmsgModel.Remark1 = teacherArr[i].Exp_IntTryParse();
-
pushmsgModel.AddTime = DateTime.Now;
-
pushmsgModel.SendTime = DateTime.Now;
-
pushmsgModel.Remark2 = "";
-
pushmsgModel.Remark3 = false;
-
pushmsgDal.Admin_Add(pushmsgModel);
-
-
strLog = "向设备推送消息成功\r\n请求参数=" + strParms + "\r\n";
-
|
请发表评论