简体   繁体   中英

Error 400 GCM Invalid Request json

I am completely new to this kind of programming so I don't really know if there is an answer to this already, but I weren't able to find it. So I am testing to see if I can get a dry-run gcm message to work without errors.

The error I get is the error 400 Invalid Request, and it's saying something about the json being invalid, so I have assumed the problem has to do with string manipulation or the definition of postdata, but I can't figure it out. Most of the code is just copy pasted anyway so one could believe that others in a similar situation will get the same error, if they copy from the same source.

And also I have put in actual values for the "lorem"s.

This is the only code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

namespace ServerGMC
{
    public class ServerGMC
    {
        static void Main ()
        {
            // Prepares and calls the function to send message
            List<string> RedIdList = new List<string>(1) { "aaaaaaaaaaaaaaaaaaaaaaaa" };
            RedIdList.TrimExcess();
            Console.WriteLine(SendNotification(RedIdList, "HelloWorld", "test", 220299));
            Console.Read();
        }
        static public string SendNotification(List<string> deviceRegIds, string message, string title, long id)
        {
            try
            {
                string regIds = string.Join("\",\"", deviceRegIds);

                string AppId = "lorem";
                var SenderId = "lorem";

                NotificationMessage nm = new NotificationMessage();
                nm.Title = title;
                nm.Message = message;
                nm.ItemId = id;

                var value = new JavaScriptSerializer().Serialize(nm);
                WebRequest wRequest;
                wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
                wRequest.Method = "post";
                wRequest.ContentType = " application/json;charset=UTF-8";
                wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));
                wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));

                string postData = "{\"collapse_key\":\"standard\",\"time_to_live\":108,\"delay_while_idle\":true,\"dry_run\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + regIds + "\"]}";
                //string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&date.time=" + System.DateTime.Now.ToString() + "&registration_ids=" + regIds + "";
                Console.WriteLine(postData);

                Byte[] bytes = Encoding.UTF8.GetBytes(postData);
                wRequest.ContentLength = bytes.Length;

                Stream stream = wRequest.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();

                WebResponse wResponse = wRequest.GetResponse();

                stream = wResponse.GetResponseStream();

                StreamReader reader = new StreamReader(stream);

                String response = reader.ReadToEnd();

                HttpWebResponse httpResponse = (HttpWebResponse)wResponse;
                string status = httpResponse.StatusCode.ToString();

                reader.Close();
                stream.Close();
                wResponse.Close();

                if (status == "")
                {
                    return response;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.WriteLine();
                return "";
            }
        }
        private class NotificationMessage
        {
            public string Title;
            public string Message;
            public long ItemId;
        }
    }
}

The postData isn't properly formatted in JSON. If you check it out using an online formatting tool, it looks like this

{
    "collapse_key":"standard",
    "time_to_live":108,
    "delay_while_idle":true,
    "dry_run":‌​true,
    "data":{
        "message":"{"Title":"test",
        "Message":"HelloWorld",
        "ItemId":220299}",
        "time":"22/04/2016 13:04:38"
    },
    "registration_ids":["aaaaaaaaaaaaaaaaaaaaaaaa"]
}

You can either remove the data.message node and place its properties in data , or use a 3rd-party JSON parser or System.Web.Helpers.Json.Decode (which were suggested in this issue )

Hopefully this helps with the issue.

Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM