I am trying to send FCM push alarm to an Android app using HTTP request in C#. I've seen some examples and wrote them as a reference, but I ran into problems where I didn't expect them.
I got a data stream returned through an HTTP request, and I wrote data to it with the Write() method, but an exception occurred.
Here is my code.
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();
}
}
}
}
}
How I solve it???