【问题标题】:Google FCM gives me BadRequest when I use .NET Core HttpClient当我使用 .NET Core HttpClient 时,Google FCM 给了我 BadRequest
【发布时间】:2019-10-01 13:25:16
【问题描述】:

我正在尝试使用 FCM API 在 android 应用程序上发送推送通知。如果我使用 Insomnia 或 Postman 之类的 HTTP 客户端,效果会很好。下面是画面吗:

和标题:

当然,我有一个注册 ID 和 FCM 服务器密钥,而不是 xxx

但我需要从我的C# 代码中发送相同的内容。我总是有BadRequest。我不明白为什么。

这是我的代码:

var json = JsonConvert.SerializeObject(new
{
    to = customer.FcmRegistrationId,
    notification = new
    {
        body = push.PushBody,
        title = push.PushTitle,
        sound = "default"
    }
});

var content = new StringContent(json, Encoding.UTF8, "application/json");

var request = new HttpRequestMessage
{
    RequestUri = new Uri("https://fcm.googleapis.com/fcm/send"),
    Content = content,
};

request.Headers.TryAddWithoutValidation("Authorization", 
    "key=" + customer.FCMServerKey);

HttpResponseMessage response;

using (var client = new HttpClient())
{
    response = await client.SendAsync(request);
}

response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync(); 

在我总是得到这个答案之前,我很伤心:

请帮帮我!

【问题讨论】:

  • 你能添加一个像 fiddler 这样的代理来检查这两个有效载荷吗?这就是我要开始的地方。添加代理并检查 Headers、Body 等
  • 谢谢。我会尝试。我以前从没用过。
  • 错误请求几乎总是在您的有效负载的一个或多个字段上出现拼写错误。请记住,序列化将导致一对一的变量发送到字段。因此,请检查您的班级成员名称以确保它映射邮递员有效负载。
  • 我检查了所有字段。我已经制作了 json 转储并将其放入 Insomnia http 客户端。我对服务器身份验证密钥做了同样的事情。一切正常!
  • 然后您需要检查 Http 客户端创建的确切有效负载才能弄清楚这一点(提琴手之类的)。

标签: c# .net-core firebase-cloud-messaging dotnet-httpclient


【解决方案1】:

我测试了一种发送推送通知的方法:使用 WebRequest.Create

请在您的 fcm 帐户中设置 devId(您在 fcm 注册设备上的 reg-id)、SERVER_API_KEY 和 SENDER_ID。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace SendMsgByFCM
{
    public partial class Form1 : Form
    {

        AndroidGCMPushNotification fcmPush = new AndroidGCMPushNotification();


        public Form1()
        {
            InitForm();
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
             **devId** = "faxgYiWv4Sk:APA91bGehlGNNGaE20djfaJ5xzQst_b190GvrEwm_yvPsZvY-.....";
            fcmPush.SendNotification(devId, 'message ...' );
            MessageBox.Show( "msg send" );
        }
    }

    public class AndroidGCMPushNotification
    {

        public string SendNotification(string deviceId, string message)
        {
            string **SERVER_API_KEY** = "AAAADtSR7s8:APA91bHhhsjRMeL2gH6Qzv5BbdJyshOtgJ-J....";

            var **SENDER_ID** = "636988888888";
            var value = message;
            WebRequest tRequest;
            tRequest = **WebRequest.Create**("https://fcm.googleapis.com/fcm/send");
            tRequest.Method = "post";
            tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
            tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));

            tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

            string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";
            Console.WriteLine(postData);
            Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            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;
        }
    }
}

【讨论】:

  • 是 WinForms 吗?它适用于 .NET Core Web Api 吗?
【解决方案2】:

我已经在以下代码的帮助下解决了这个问题:

using (var client = new HttpClient())
{

client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"key={ServerKey}");
var obj = new
{
    to = Id,
    notification = new
    {
        title = Title,
        body = Message

    }
};

//serialize object data to json
string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
// create an http string content
var data = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("https://fcm.googleapis.com/fcm/send", data);
return response.StatusCode;

...

完整来源在这里https://github.com/frankodoom/Firebase.Notification/blob/master/Firebase.Network.Standard/Firebase.cs

我不知道为什么,但原始来源中的 datatext 不起作用。使用titlebody

【讨论】:

    猜你喜欢
    • 2021-06-04
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 2019-10-02
    相关资源
    最近更新 更多