未经授权称谷歌GCM时(Unauthorized when calling Google GCM)

2019-06-26 04:49发布

我尝试使用谷歌GCM发送推送通知。 但得到引发WebException,指出远程服务器返回401 unautorized。 我不能foung为什么doen't工作。

任何人都知道为什么它不工作?

这里是我的代码:

            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);

           HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");


            Request.Method = "POST";
            Request.KeepAlive = false;

            string postData = "{ 'registration_ids': [ '"+registrationId+"' ], 'data': {'message': '"+message+"'}}";

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            Request.ContentType = "application/json";
            //Request.ContentLength = byteArray.Length;


            //Request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + AuthString);
            Request.Headers.Add(HttpRequestHeader.Authorization, "Authorization: key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y");
            //-- Delegate Modeling to Validate Server Certificate --//


            //-- Create Stream to Write Byte Array --// 
            Stream dataStream = Request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            //-- Post a Message --//
            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.ReadLine();
            Reader.Close();

Answer 1:

丹尼尔 - 多德没有与GCM文件的问题! 使用浏览器密钥在服务器API密钥的地方的授权密钥。 它将工作。



Answer 2:

OK,我只是在黑暗中拍摄在这里。 看看这一行:

Request.Headers.Add(HttpRequestHeader.Authorization, "Authorization: key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y");

它不应该是:

Request.Headers.Add(HttpRequestHeader.Authorization, "key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y");

因为你告诉它这是一个Authorization头,没有必要添加的授权:“再次,不是吗?

此外,确保字符串常量“HttpRequestHeader.Authorization”是“授权”。



文章来源: Unauthorized when calling Google GCM