0

I'm attempting to create a console based server application to send push notifications to android clients following this tutorial here

The tutorial has a fairly straight forward code for connecting to the GCM service to send notification to the client which is like so:

 public const string API_KEY = "AIzaS...jhqOydFCU";
    public const string MESSAGE = "Hello!";

    static void Main(string[] args)
    {
        var jGcmData = new JObject();
        var jData = new JObject();

        jData.Add("message", MESSAGE);
        jGcmData.Add("to", "/topics/global");
        jGcmData.Add("data", jData);

        var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
        try
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.TryAddWithoutValidation(
                    "Authorization", "key=" + API_KEY);

                Task.WaitAll(client.PostAsync(url,
                    new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
                        .ContinueWith(response =>
                        {
                            Console.WriteLine(response);
                            Console.WriteLine("Message sent: check the client device notification tray.");
                        }));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Unable to send GCM message:");
            Console.Error.WriteLine(e.StackTrace);
        }
    }

I get 401 unauthorized error in the response header from the server. I tried with different API keys but the result is the same. I'm not sure what could be the reason for this. My client application doesn't receive any notification sent by the server.

Ahmed Mujtaba
  • 2,110
  • 5
  • 36
  • 67

1 Answers1

0

Glad that its already working for you.

In previous cases, its caused by not using a Server Key. But now that the developer console has been updated, its usually observed for the developers to try to restrict (whitelist) the API key to your webservice and/or IP address and wait for about 5 minutes for the changes to take effect.

Only Server API keys would work for GCM/FCM. But, with the recent changes in the developer console, what I can suggest is to whitelist the server calling it (local/remote hosted).

adjuremods
  • 2,938
  • 2
  • 12
  • 17