How to send push notification to more then 1000 us

2019-07-25 13:17发布

问题:

I'm using asp.net c# to send push notifications to users through GCM. This is my code to send notification.

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

SendGCMNotification Function:-

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

It is working properly and notification delivered properly to 1000 users.But now i have more then 1000 users and i have to send notifications to them all,but in gcm documentation it is specified that we can pass 1000 registrations ids at one time.what can i do to send notification to all user?Any help will be appriciated

回答1:

Well probably you get exception because you are not setting content type. I found article how to send data and rewrote it to your needs. You also would need to install Json.Net package

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

Then you can call method

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