【发布时间】:2020-11-18 03:11:10
【问题描述】:
我正在尝试使用 C# 中的 HTTP 请求将 FCM 推送警报发送到 Android 应用程序。我看过一些例子并写了它们作为参考,但我遇到了我没想到的问题。
我得到一个通过HTTP请求返回的数据流,我用Write()方法向它写入数据,但是发生了异常。
这是我的代码。
public void PushNotification()
{
const string FCM_URL = "https://fcm.googleapis.com/v1/projects/xxx/messages:send HTTP/1.1";
const string SERVER_KEY = "xxxxxx";
const string SENDER_ID = "xxxxx";
string postbody;
Byte[] byteArr;
object payload;
WebRequest wReq;
wReq = WebRequest.Create(FCM_URL);
wReq.Method = "post";
wReq.Headers.Add(string.Format("Autorization:key={0}", SERVER_KEY));
wReq.Headers.Add(string.Format("Sender:id={0}", SENDER_ID));
wReq.ContentType = "application/json";
payload = new
{
to = "/topics/all",
priority = "high",
content_available = true,
notification = new
{
body = "Test",
title = "Test",
badge = 1
},
data = new
{
key1 = "val1",
key2 = "val2"
}
};
postbody = JsonConvert.SerializeObject(payload).ToString();
byteArr = Encoding.UTF8.GetBytes(postbody);
wReq.ContentLength = byteArr.Length;
using (Stream dStream = wReq.GetRequestStream())
{
dStream.Write(byteArr, 0, byteArr.Length);
using (WebResponse wResp = wReq.GetResponse()) //Exception: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
{
using (Stream dStreamResp = wResp.GetResponseStream())
{
if (dStreamResp != null) using (StreamReader wReader = new StreamReader(dStreamResp))
{
string sRespFromServer = wReader.ReadToEnd();
}
}
}
}
}
我是怎么解决的???
【问题讨论】:
标签: c# firebase-cloud-messaging