Android C2DM Invalidregistration

2019-06-01 19:42发布

问题:

I have created an android app, that registering to google c2dm service. And It's getting a registration_id token from c2dm services successfully.

I already signed Android Cloud to Device Messaging form and I received confirmation email from c2dm service.

Everything seems ok in client side, it's getting registration_id in simulator environment. So, it's ok.

But, On server side, It's authenticating google service, it's receiving Auth code then it's invoking to c2dm send url with below code.

  public void SendMessage(string registrationId, string data)
    {
        ServicePointManager.ServerCertificateValidationCallback += delegate(
                                            object sender,
                                            X509Certificate certificate,
                                            X509Chain chain,
                                            SslPolicyErrors sslPolicyErrors)
        {
            return true;
        };

        string collapseKey = Guid.NewGuid().ToString("n");          

        string url = "https://android.apis.google.com/c2dm/send";
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "POST";
        request.Headers.Add("Authorization", "GoogleLogin auth=DQAAAKYAAACE_0NqG8Sj5lBf4YSPXs_ltQbTzPsAL5u1Q1KGF...");

        string px = "registration_id=" + registrationId + "&collapse_key=" + collapseKey + "&data.payload=" + data;
        string encoded = HttpUtility.UrlEncode(px);

        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] buffer = encoding.GetBytes(encoded);

        Stream newStream = request.GetRequestStream();
        newStream.Write(buffer, 0, buffer.Length);
        newStream.Close();




         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         if(response.StatusCode == HttpStatusCode.OK)
         {
             Stream resStream = response.GetResponseStream();
             StreamReader sr = new StreamReader(resStream);
             Console.Write(sr.ReadToEnd());
             sr.Close();
             resStream.Close();
         }
         Console.WriteLine();
         Console.ReadLine();
    }

It's still receiving Error=InvalidRegistration response from c2dm service.

What I'm doing wrong ?

回答1:

Ok, It solved. I removed HttpUtility.UrlEncode(px); and everything worked as I expected.



回答2:

I had this problem for a long time until I set the ContentType to-

application/x-www-form-urlencoded

You need to set it to that for both

  • the authentication stage and,
  • the send message.

I then got the NotRegistered error but that is due to not using the same account on the phone as the sender for the server authentication.

Hope that helps others.