简体   繁体   中英

GCM giving error: (401) Unauthorized

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

在此处输入图片说明

server key 1

and sender id from

在此处输入图片说明

Project number

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM