c# - 调用 Google GCM 时未经授权

标签 c# android httpwebrequest unauthorized google-cloud-messaging

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

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

这是我的代码:

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

enter image description here

最佳答案

Daniel - 伙计,GCM 文档有问题!在 Server API key 的地方使用 Browser key 作为 authorization key 。它会起作用。

关于c# - 调用 Google GCM 时未经授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11431261/

相关文章:

c# - 响应式(Reactive)扩展清理

c# - 将正确的 header 值发送到从 Angular $http 到 asp.net webapi 的 Preflight 请求时出错

android - 是否有任何 Android 浏览器引用/文档?

c# - 如何在 C# 中解析未知的日期时间格式

android - 如何通过单击选项菜单项在 web View 中加载不同的 html 页面?

android - 同时进行 Espresso 自动和手动测试

http - 使用 C# 从 url 获取 HTTP 响应

http - PUT 和 POST 请求是否需要/期望有一个请求主体?

c# - 客户端机器是否需要安装 .NET 才能运行 ASP.NET Web 应用程序

c# - 如何 try catch 未找到的程序集