本文介绍了未经授权调用谷歌GCM时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I trying to use Google GCM for sending push notifications. But get a WebException that says that the remote server returns 401 unautorized. I can't foung why it doen't work.

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

Anyone that knows why it doesn't work?

下面是我的code:

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

推荐答案

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

Daniel - Dude there is an issue with the GCM documentation ! Use Browser key as the authorization key at the place of Server API key . It will work.

这篇关于未经授权调用谷歌GCM时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 14:45