0

我正在使用 c# webservices 将注册 ID 传递给 GCM。我有两部安卓手机,我有有效的注册 ID。当我单独传递它们时,GCm 不会返回任何错误并且设备会收到通知。但是当我尝试将它们作为 JSON 一起传递时,我收到错误消息"Error = missing registration".

以下是将注册 ID 传递给 GCM 的 Web 服务的代码。

 public string Notify(string deviceId, string message)
    {

        WebRequest tRequest;
        tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
        tRequest.Method = "post";
        tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
//        tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
        tRequest.Headers.Add(HttpRequestHeader.Authorization, "key=AIzaSyCUJX_f_NZzYbigWMDK9U5vkzZ9mPiK8jA");
       tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
       int count = 2;

           SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["Login"]);
           conn.Open();

           string send_notification = "select RegId from REG_ID ";//where RegId <> '"+deviceId+"'";
           SqlCommand cmd2 = new SqlCommand(send_notification, conn);
           DataSet ds2 = new DataSet();
           SqlDataAdapter adapter2 = new SqlDataAdapter(cmd2);
           adapter2.Fill(ds2);
           int count1 = ds2.Tables[0].Rows.Count;
           registration[] r = new registration[count1];
           for (int i = 0; i < count1; i++)
           {
               r[i] = new registration();
               r[i].registration_ids = ds2.Tables[0].Rows[i]["RegId"].ToString();
           } 
        JavaScriptSerializer js = new JavaScriptSerializer();
        string strJson = js.Serialize(r);
        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= "+ deviceId + "";
        Console.WriteLine(strJson);
        Byte[] byteArray = Encoding.UTF8.GetBytes(strJson);
        tRequest.ContentLength = byteArray.Length;

        Stream dataStream = tRequest.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        WebResponse tResponse = tRequest.GetResponse();

        dataStream = tResponse.GetResponseStream();

        StreamReader tReader = new StreamReader(dataStream);

        String sResponseFromServer = tReader.ReadToEnd();

        tReader.Close();
        dataStream.Close();
        tResponse.Close();
        return sResponseFromServer;
    }

我是开发新手,可能会遗漏一些非常简单的东西。任何帮助表示赞赏..在此先感谢

4

1 回答 1

2

您的 JSON 应如下所示:

{ "data": {
    "score": "5x1",
    "time": "15:10"
  },
  "registration_ids": ["4", "8", "15", "16", "23", "42"]
}
  • 您发布的代码混合了 JSON 格式和纯文本格式。
  • 如果您想在一个请求中发送多条消息,您应该将您的内容类型更改为application/json.
  • 从您的代码中不清楚您strJson包含什么,所以我不能说它是否有效。
  • 您的postData变量似乎属于纯文本格式,但无论如何您都不使用它。
于 2013-04-22T09:57:48.613 回答