SimplyProgrammer SimplyProgrammer - 1 month ago 9
ASP.NET (C#) Question

GCM request in Asp.net

I have reffered this link for sending GCM request and it is working perfectly fine. gcm-push-notification-with-asp-net

I referred one more link to post

JSON
how-to-post-json-to-the-server

On the basis of second link I have tried the following code.

var httprequest = (HttpWebRequest)WebRequest.Create("https://gcm-http.googleapis.com/gcm/send");
httprequest.ContentType = "application/json";
httprequest.Method = "POST";
httprequest.Headers.Add(string.Format("Authorization: key={0}", GCM.APIKey));
httprequest.Headers.Add(string.Format("Sender: id={0}", GCM.ProjectNo));

using (var streamWriter = new StreamWriter(httprequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new GCMValues
{
delay_while_idle = false,
priority = "high",
registration_id = regId,
data = new MessagesValues
{
message = message
}
});

streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httprequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}


Properties that I have used

public class GCMValues
{
public Object data { get; set; }
public bool delay_while_idle { get; set; }
public String priority { get; set; }
public String registration_id { get; set; }
}
public class MessagesValues
{
public String message { get; set; }
public DateTime? time { get; set; }
}


The problem I am facing is at line
var httpResponse =(HttpWebResponse)httprequest.GetResponse();


I am getting a response of bad request.
Where I went wrong or what could be done to pass the values in
JSON
format for
GCM
post request.
Thanks in advance.

Answer

You need registration_ids (plural) not registration_id (singular) in the JSON. It is an array of strings , not a single string value.

If you check the GCM documentation it gives all the JSON options.

Elsewhere the documentation details how to use to if you have just one token to send a notification to, as in this example:

  {
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon"
    }
  }
Comments