得到(400)不良请求。在尝试发送GCM消息时

时间:2016-07-09 02:51:44

标签: c# android .net android-studio google-cloud-messaging

我正在尝试通过C#.net

向GCM Server发送消息

我找到了一个很好的例子,我正在尝试使用

http://www.codewithasp.net/2015/11/send-message-gcm-c-sharp-single-multiple.html

问题是我得到"远程服务器返回错误:(400)错误请求。"每当我尝试从此行获取响应时出现错误

            WebResponse wResponse = wRequest.GetResponse();

我试图找到问题的原因,我将API代码从服务器更改为Android,更改为浏览器,结果是(400)错误请求或(401)未经授权。

不确定我在这里做错了什么,在示例中看起来非常简单和直接。

非常感谢帮助

这是代码

        NotificationManager nm = new NotificationManager();
        List<string> ls = new List<string>(new string[] { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" });

        nm.SendNotification(ls, " Hi.. This is a test","Hi.. Title",1);

这是班级

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

namespace WebApplication1
{

    public class NotificationManager
    {
        private class NotificationMessage
        {
            public string Title;
            public string Message;
            public long ItemId;
        }

        public NotificationManager()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public string SendNotification(List<string> deviceRegIds, string message, string title, long id)
        {
            try
            {
                string regIds = string.Join("\",\"", deviceRegIds);

                string AppId = "AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
                var SenderId = "1234567890";

                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\":\"score_update\",\"time_to_live\":108,\"delay_while_idle\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + regIds + "\"]}";

                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 ex)
            {
                return ex.ToString();
            }
        }
    }
}

以下是我获取API ID和发件人ID的方法

Sender ID

API ID

5 个答案:

答案 0 :(得分:1)

这就是我在C#中的表现:

public class VmFcmNotification
{
    public string body { get; set; }
    public string title { get; set; }
    public string icon { get; set; }
    public string text { get; set; }
    public string sound { get; set; }

}

public class VmFcmMessage
{
    /// <summary>
    /// This parameter specifies the recipient of a message.
    /// The value must be a registration token, notification key, or topic.
    /// Do not set this field when sending to multiple topics.
    /// </summary>
    public string to { get; set; }

    /// <summary>
    /// This parameter identifies a group of messages (e.g., with collapse_key: "Updates Available") that can be collapsed,
    /// so that only the last message gets sent when delivery can be resumed.
    /// This is intended to avoid sending too many of the same messages when the device comes back online or becomes active (see delay_while_idle).
    /// Note that there is no guarantee of the order in which messages get sent.
    /// Note: A maximum of 4 different collapse keys is allowed at any given time.
    /// This means a FCM connection server can simultaneously store 4 different send-to-sync messages per client app.
    /// If you exceed this number, there is no guarantee which 4 collapse keys the FCM connection server will keep.
    /// </summary>
    public string collapse_key { get; set; }

    /// <summary>
    /// This parameter, when set to true, allows developers to test a request without actually sending a message.
    /// The default value is false.
    /// </summary>
    public Boolean dry_run { get; set; }

    /// <summary>
    /// This parameter specifies a list of devices (registration tokens, or IDs) receiving a multicast message.
    /// It must contain at least 1 and at most 1000 registration tokens.
    /// Use this parameter only for multicast messaging, not for single recipients.
    /// Multicast messages (sending to more than 1 registration tokens) are allowed using HTTP JSON format only.
    /// </summary>
    public List<string> registration_ids { get; set; }


    public VmFcmNotification notification { get; set; }

}

然后我用这个函数发送:

public static Boolean SendToOneUser(String userToken, String msgTitle)
    {
        using (var client = new HttpClient())
        {
            var message = new VmFcmMessage();
            message.to = userToken;
            message.notification = new VmFcmNotification()
            {
                title = msgTitle,
                //body = desc,
                //text = desc
            };

            string postBody = JsonConvert.SerializeObject(message).ToString();

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var SERVER_KEY="key=AIza...........";
            client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", SERVER_KEY);

            var response = client.PostAsync("https://fcm.googleapis.com/fcm/send", new StringContent(postBody, Encoding.UTF8, "application/json"));
            var responseString = response.Result.Content.ReadAsStringAsync().Result;
            //TODO get response and handle send messages
            return true;
        }
    }

答案 1 :(得分:1)

嘿asmgx我想我遇到了你的问题。 我也有同样的错误,输入错误在以下行:

  

授权:键=

现在我不是一个c#类型的人;)但似乎你在添加你的密钥之前没有连接“key =”,我发现很容易出现这个错误,因为我还有第一个错误我正在尝试GCM。

所以请确保在“授权:”之后连接“key =”,(您可能需要选择错误未经授权的选项)

这是GCM网页

中的完整示例
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "data" : {
    ...
  },
}

如果这样做不起作用并且您的请求似乎没问题,请确保您将服务器地址添加到凭据中,或者只是填写其网站上的一个GCM示例中给出的虚假地址(这是像0.0.0:0000,找不到ATM所以只是在我上面添加的链接中找到它或谷歌它。)

如果两者都不起作用,请告诉我。

BTW - &gt;想想搬到火堆。

答案 2 :(得分:1)

我是您提及的本网站的作者。感谢指出错误实际问题在postData字符串中。我们用双引号括起我们的值(“像这样”),但它是一个json字符串,所以我们不需要这样做。只需在postData字符串中删除双引号值,它就会对你有效。

所以只需改变这个

string postData = "{\"collapse_key\":\"score_update\",\"time_to_live\":108,\"delay_while_idle\":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\":true,\"data\": { \"message\" : " + value + ",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + regIds + "\"]}";

你已经完成了。

我还在the post on the link更正了它,以便其他访问者可能不会遇到同样的问题。

答案 3 :(得分:1)

通过HttpWebRequest s发送GCM消息时遇到了同样的错误:

  

远程服务器返回错误:(400)错误请求。

     

StatusDescription:InvalidTokenFormat

但问题不一样。我刚才有错误的网址:

"https://fcm.googleapis.com/fcm/send/" //wrong
"https://fcm.googleapis.com/fcm/send"

我花了更长的时间才愿意承认这一点。而且我想从这种误导性的错误信息中为其他人带来麻烦。

答案 4 :(得分:0)

仅供参考:如果您的设备令牌to: XXX错误或来自错误的项目,您也会获得此代码。