5

這是我爲GCM創建的示例服務器。GCM的迴應是:Error = NotRegistered

class Program2 
{ 
    public static string SenderId = "318115091714"; 
    public static string RegistrationID = "APA91bF9hn6VeessobraNuauBcrFdlJ9eH1eVb44FAQ2oawerBeFWS48IEIFTPo8fdvWm93hwFY0tKszpPuSObPbTqgW-za1RLhCw-GDCn4JQZLQ-CmGwnnr6F5X8gYhNa2DNvFhCEM7HNgvdxtcnBqVX0dVnEynXQ"; 
    public static string ApiKey = "AIzaSyAl2HdB4bbukkcmJwoxUmhof15IAiuJ16U"; 
    public static string Message = "Testing GCM Server"; 
    public static string ApplicationId = "com.google.android.gcm.demo.app"; 

    /// <summary> 
    /// Main method 
    /// </summary> 
    public static void Main(string[] args) 
    { 
     try 
     { 
      Program2 objProgram2 = new Program2(); 

      Console.WriteLine("\nPlease wait while GCM server is processing..."); 
      string Text = objProgram2.SendMessage(); 
      Console.WriteLine("\nSendMessage Response: " + Text); 

      Console.ReadLine(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("\n" + ex.Message); 
      Console.WriteLine("\n" + ex.StackTrace); 
      Console.ReadLine(); 
     } 
    } 

    /// <summary> 
    /// Send Push Message to Device 
    /// </summary> 
    public string SendMessage() 
    { 
                 //-- Create Query String --// 
     string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.Message=" + Message + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + RegistrationID + ""; 
     //Console.WriteLine(postData); 
     Byte[] byteArray = Encoding.UTF8.GetBytes(postData); 

                //-- Create GCM Request Object --// 
     HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send"); 
     Request.Method = "POST"; 
     Request.KeepAlive = false; 
     Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; 
     Request.Headers.Add(string.Format("Authorization: key={0}", ApiKey)); 
     Request.Headers.Add(string.Format("Sender: id={0}", SenderId)); 
     Request.ContentLength = byteArray.Length; 

             //-- Delegate Modeling to Validate Server Certificate --// 
     ServicePointManager.ServerCertificateValidationCallback += delegate(
        object 
        sender, 
        System.Security.Cryptography.X509Certificates.X509Certificate 
        pCertificate, 
        System.Security.Cryptography.X509Certificates.X509Chain pChain, 
        System.Net.Security.SslPolicyErrors pSSLPolicyErrors) 
     { 
      return true; 
     }; 

              //-- 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)) 
     { 
      return "Unauthorized - need new token"; 

     } 
     else if (!ResponseCode.Equals(HttpStatusCode.OK)) 
     { 
      return "Response from web service isn't OK"; 
      //Console.WriteLine("Response from web service is not OK :"); 
      //Console.WriteLine(((HttpWebResponse)Response).StatusDescription); 
     } 

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

     return responseLine; 
    } 
} 

用這些有效的值和鍵運行它後,我收到了這個響應。

Please wait while GCM server is processing... 

SendMessage Response: Error=NotRegistered 

我得到Error=NotRegistered。這個響應甚至沒有在android開發人員指南中指定。我應該得到這個迴應的原因是什麼?任何人都可以幫我解決這個問題嗎?提前致謝。

回答

7

我發現爲什麼發生的原因。可能有六種類型的迴應。以下是回覆列表及其含義。

{ "message_id": "1:0408" } - success 
{ "error": "Unavailable" } - should be resent 
{ "error": "InvalidRegistration" } - had an unrecoverable error (maybe the value got corrupted in the database) 
{ "message_id": "1:1516" } - success 
{ "message_id": "1:2342", "registration_id": "32" } - success, but the registration ID should be updated in the server database 
{ "error": "NotRegistered"} - registration ID should be removed from the server database because the application was uninstalled from the device 

我得到了錯誤消息6.新的發件人ID,註冊ID和API密鑰我的上述代碼正在工作。

+0

我收到迴應'InvalidRegistration'迴應,原因是什麼? – yadavr 2017-05-12 16:12:21

3

我不是服務器人,但最近查看了GCM服務器代碼來解決問題。所以在這裏我找到了什麼:

你的代碼行設置API密鑰:

Request.Headers.Add(string.Format("Authorization: key={0}", ApiKey)); 

不看我的權利。該鍵=詞應該要連接到API密鑰,然後您的線路是這樣的:

Request.Headers.Add("Authorization", "key=" + ApiKey)); 

這是我的到底是什麼工作。

和發件人ID,我們有不同的方法,所以檢查這行代碼太:

Request.Headers.Add(string.Format("Sender: id={0}", SenderId)); 
+1

這些行不會產生完全相同的字符串作爲結果嗎?據我所見,'key = {0}'會將'ApiKey'放在'='之後。 – spacediver 2015-11-27 15:29:21