错误400 GCM无效请求json

时间:2016-04-21 19:38:06

标签: c# .net json google-cloud-messaging

我对这种编程完全陌生,所以我不知道是否已经有了答案,但我无法找到它。因此,我正在测试是否可以无干扰地运行干运行gcm消息。

我得到的错误是错误400无效请求,并且它说json无效,所以我假设问题与字符串操作或postdata的定义有关,但我可以&# 39;弄清楚。大多数代码只是复制粘贴,所以如果他们从相同的源复制,可以相信处于类似情况的其他人会得到相同的错误。

而且我已经为" lorem"提供了实际价值。

这是唯一的代码:

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;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

postData未正确格式化为JSON。如果您使用在线格式化工具查看它,它看起来像这样

{
    "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"]
}

您可以删除data.message节点并将其属性放在data中,也可以使用第三方JSON解析器或System.Web.Helpers.Json.Decodethis issue中建议的)

希望这有助于解决这个问题。

快乐的编码!