7

我尝试使用 Google GCM 发送推送通知。但是得到一个 WebException ,表明远程服务器未经授权返回 401。我不知道为什么它不起作用。

有谁知道为什么它不起作用?

这是我的代码:

            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();

在此处输入图像描述

4

2 回答 2

11

Daniel-Dude GCM 文档有问题!在 Server API key 的地方使用 Browser key 作为授权 key。它会起作用的。

于 2012-07-11T11:09:22.700 回答
10

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

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

不应该是:

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

既然您告诉它这是一个 Authorization 标头,则无需再次添加“Authorization:”,对吗?

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

于 2012-07-11T23:19:12.037 回答