I am trying to write the web api in c# to send push notification in android device. which is giving me the 401 unauthorized error. i have follow all the step to send the notification. i am not able to understand why i am not authorize user.
here is my function to send notification.
public String Post(string message, string regId)
{
try
{
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key=**server-api-key**"));
tRequest.Headers.Add(string.Format("Sender: id=**sender-id**"));
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ message + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + regId + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
catch (Exception e)
{
throw;
}
}
Get the api key from
server key 1
and sender id from
Project number
My post function accept the message and regId which is device id.