远程服务器返回错误:在C#中GCM响应unathorized(401) [英] remote server returned an error: (401) unathorized in C# GCM response

查看:506
本文介绍了远程服务器返回错误:在C#中GCM响应unathorized(401)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了这个问题张贴在一千的地方,我曾尝试已为他人工作的所有解决方案,但我不能得到这个工作对我来说。我用这个岗位作为我的底线项目,即时通讯称谷歌GCM在使用(未经授权)。我已经试过这两个API密钥,并没有成功的关键浏览器

I have seen this question posted in a thousand places and I have tried all the solutions that have worked for others but I am not able to get this to work for me. I used this post as my baseline for the project that Im using (Unauthorized when calling Google GCM). I have tried both the API key and the browser key with no success.

下面是我的code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

using System.IO;

namespace GCMTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string BrowserAPIKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

            string message = "some test message";
            string tickerText = "example test GCM";
            string contentTitle = "content title GCM";
            string postData = "{ \"registration_ids\": [ \"" + txtRegistrationID.Text + "\" ], \"data\": {\"tickerText\":\"" + tickerText + "\", \"contentTitle\":\"" + contentTitle + "\", \"message\": \"" + message + "\"}}";

            string response = SendGCMNotification(BrowserAPIKey, postData);
        }

        private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
        {
            // from here:
            // http://stackoverflow.com/questions/11431261/unauthorized-when-calling-google-gcm
            //
            // original:
            // http://www.codeproject.com/Articles/339162/Android-push-notification-implementation-using-ASP

            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);

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

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

            Request.Method = "POST";
            Request.KeepAlive = false;
            Request.ContentType = postDataContentType;
            //Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
            Request.Headers.Add(HttpRequestHeader.Authorization, String.Format("key={0}", apiKey));
            Request.ContentLength = byteArray.Length;

            //Stream dataStream;
            try
            {
                Stream dataStream = Request.GetRequestStream();

                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            //
            //  SEND MESSAGE
            try
            {
                WebResponse Response = Request.GetResponse();

                HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;

                if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
                {
                    MessageBox.Show("Unauthorized - need new token");

                }
                else if (!ResponseCode.Equals(HttpStatusCode.OK))
                {
                    MessageBox.Show("Response from web service isn't OK");
                }

                StreamReader Reader = new StreamReader(Response.GetResponseStream());
                string responseLine = Reader.ReadToEnd();
                Reader.Close();

                return responseLine;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            return "error";
        }


        public static bool ValidateServerCertificate(
                                                  object sender,
                                                  X509Certificate certificate,
                                                  X509Chain chain,
                                                  SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
    }

}

它在这条线犯错的:

Its erring on this line:

WebResponse Response = Request.GetResponse();

通过以​​下信息:
远程服务器返回错误:未经授权(401)

With the following message: "The remote server returned an error: (401) Unauthorized."

形式允许设备注册ID的输入。如果我能得到这个工作将被改变是在生产环境中更实用。该应用程序是我的本地机器上运行,但现在最终将驻留在远程服务器上。

The form allows an input of a device registration id. If I can get this working it will be altered to be more usable in a production environment. The application is running on my local machine right now but will ultimately reside on a remote server.

任何帮助,我能得到将是极大的AP preciated。我一直在阅读这个帖子了一个星期,我一直没能取得任何进展。有一件事,我认为可能会引起这个问题,即时通讯服务器上运行这个本地,而不是事实。这是否要求必须来自于在引荐在浏览器项中列出的地址是什么?

Any help that I can get would be GREATLY appreciated. I have been reading posts about this for a week now and I haven't been able to make any progress. One thing that I think might be causing this problem is the fact that Im running this locally instead of on the server. Does this request need to come from the address that is listed in the "referer" in the browser key?

再次感谢!

推荐答案

如果您使用的是浏览器密钥,您应该删除键允许的引荐,使它会说引用的任何允许。这将允许您从本地运行的服务器发送通知。

If you are using a Browser Key, you should remove the allowed referrers of that key, so that it would say Any referrer is allowed. This would allow you to send the notifications from a locally run server.

否则,您就可以使用该浏览器密钥只能从Web站点在指定的域允许的引荐

Otherwise, you'll be able to send GCM messages using that Browser Key only from Web Sites that have the domain specified in allowed referrers.

这篇关于远程服务器返回错误:在C#中GCM响应unathorized(401)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆