Google 当我使用 .NET Core HttpClient 时,FCM 给了我 BadRequest
Google FCM gives me BadRequest when I use .NET Core HttpClient
我正在尝试使用 FCM API 在 android 应用程序上发送推送通知。如果我使用像 Insomnia 或 Postman 这样的 HTTP 客户端,它会很好用。下面是画面吗:
和headers:
当然,我有一个注册 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();
因为我以前一直很伤心,所以我总是有这样的答案:
请帮帮我!
我测试了一种发送推送通知的方法:使用 WebRequest.Create
请设置 devId(您在 fcm 注册设备上的注册 ID),SERVER_API_KEY 和 SENDER_ID 来自您的 fcm 帐户。
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() + "®istration_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;
}
}
}
我已经借助以下代码解决了这个问题:
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;
...
我不知道为什么,但原始来源中的 data
和 text
不起作用。使用 title
和 body
.
我正在尝试使用 FCM API 在 android 应用程序上发送推送通知。如果我使用像 Insomnia 或 Postman 这样的 HTTP 客户端,它会很好用。下面是画面吗:
和headers:
当然,我有一个注册 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();
因为我以前一直很伤心,所以我总是有这样的答案:
请帮帮我!
我测试了一种发送推送通知的方法:使用 WebRequest.Create
请设置 devId(您在 fcm 注册设备上的注册 ID),SERVER_API_KEY 和 SENDER_ID 来自您的 fcm 帐户。
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() + "®istration_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;
}
}
}
我已经借助以下代码解决了这个问题:
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;
...
我不知道为什么,但原始来源中的 data
和 text
不起作用。使用 title
和 body
.