【问题标题】:How to send push notification to more then 1000 user through GCM如何通过 GCM 向 1000 多个用户发送推送通知
【发布时间】:2016-08-26 19:58:38
【问题描述】:

我正在使用 asp.net c# 通过 GCM 向用户发送推送通知。这是我发送通知的代码。

string RegArr = string.Empty;
RegArr = string.Join("\",\"", RegistrationID);      // (RegistrationID) is Array of endpoints

string message = "some test message";
string tickerText = "example test GCM";
string contentTitle = "content title GCM";
 postData =
"{ \"registration_ids\": [ \"" + RegArr + "\" ], " +
"\"data\": {\"tickerText\":\"" + tickerText + "\", " +
"\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";

string response = SendGCMNotification("Api key", postData);

发送GCM通知功能:-

private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
    {

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        //  CREATE REQUEST
        HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
        Request.Method = "POST";
        Request.KeepAlive = false;
        Request.ContentType = postDataContentType;
        Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
        Request.ContentLength = byteArray.Length;

        Stream dataStream = Request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
        //
        //  SEND MESSAGE
        try
        {
            WebResponse Response = Request.GetResponse();
            HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
            if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
            {
                var text = "Unauthorized - need new token";
            }
            else if (!ResponseCode.Equals(HttpStatusCode.OK))
            {
                var text = "Response from web service isn't OK";
            }
            StreamReader Reader = new StreamReader(Response.GetResponseStream());
            string responseLine = Reader.ReadToEnd();
            Reader.Close();

            return responseLine;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return "error";
    }

它工作正常,通知正确发送给 1000 个用户。但是现在我有超过 1000 个用户,我必须向他们所有人发送通知,但是在 gcm 文档中指定我们可以一次传递 1000 个注册 ID .我能做些什么来向所有用户发送通知?任何帮助都会得到满足

【问题讨论】:

  • 为什么不拆分做2个请求?
  • @VolodymyrBilyachat 你的意思是说我拆分了数组然后使用循环执行此操作?
  • 没错。因为如果它是 API 的限制,我不认为你可以用它做任何事情,所以我会在循环中这样做
  • @VolodymyrBilyachat 实际上我做的和你说的完全一样,但它不起作用,也许我在代码中做错了什么。你能给我一个代码示例吗

标签: c# asp.net push-notification google-cloud-messaging


【解决方案1】:

你可能会因为没有设置内容类型而得到异常。我找到了article how to send data 并根据您的需要重写了它。您还需要安装 Json.Net 包

public class NotificationManager
    {
        private readonly string AppId;
        private readonly string SenderId;

        public NotificationManager(string appId, string senderId)
        {
            AppId = appId;
            SenderId = senderId;
            //
            // TODO: Add constructor logic here
            //
        }

        public void SendNotification(List<string> deviceRegIds, string tickerText, string contentTitle, string message)
        {
            var skip = 0;
            const int batchSize = 1000;
            while (skip < deviceRegIds.Count)
            {
                try
                {
                    var regIds = deviceRegIds.Skip(skip).Take(batchSize);

                    skip += batchSize;

                    WebRequest wRequest;
                    wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
                    wRequest.Method = "POST";
                    wRequest.ContentType = " application/json;charset=UTF-8";
                    wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));
                    wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));

                    var postData = JsonConvert.SerializeObject(new
                    {
                        collapse_key = "score_update",
                        time_to_live = 108,
                        delay_while_idle = true,
                        data = new
                        {
                            tickerText,
                            contentTitle,
                            message
                        },
                        registration_ids = regIds
                    });

                    var bytes = Encoding.UTF8.GetBytes(postData);
                    wRequest.ContentLength = bytes.Length;

                    var stream = wRequest.GetRequestStream();
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();

                    var wResponse = wRequest.GetResponse();

                    stream = wResponse.GetResponseStream();

                    var reader = new StreamReader(stream);

                    var response = reader.ReadToEnd();

                    var httpResponse = (HttpWebResponse) wResponse;
                    var status = httpResponse.StatusCode.ToString();

                    reader.Close();
                    stream.Close();
                    wResponse.Close();

                    //TODO check status
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

然后就可以调用方法了

 var notificationManager = new NotificationManager("AppId", "SenderId");
 notificationManager.SendNotification(Enumerable.Repeat("test", 1010).ToList(), "tickerText", "contentTitle", "message");

【讨论】:

  • 感谢您的回复。我已经通过了内容类型“Request.ContentType = application/json;”。我的问题是通过使用循环解决的。我也试过这个解决方案,它工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 2017-01-08
  • 1970-01-01
相关资源
最近更新 更多