2

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() + "&registration_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

enter image description here

server key 1

and sender id from

enter image description here

Project number

My post function accept the message and regId which is device id.

Rhushikesh
  • 3,630
  • 8
  • 45
  • 82

1 Answers1

0

I don't know C# and may be missing something. It looks like your post data is not in JSON format. I don't see any braces. This SO question has examples of how to post JSON-formated data.

Also, try validating your API key using curl as explained in this example.

Community
  • 1
  • 1
Bob Snyder
  • 37,759
  • 6
  • 111
  • 158