Could you provide a simple code (or a link) to send a simple message from my C# server to Android devices via Downstream HTTP JSON?
I use next simple c# code to send messages using Downstream HTTP Plain Text. But I need to do it with JSON because I need to use the Priority field.
private string SendMessageUsingGCM(String sRegistrationId, string sTextToSend, string sCollapseKey)
{
String GCM_URL = @"https://gcm-http.googleapis.com/gcm/send";
bool flag = false;
string sError = "";
StringBuilder sb = new StringBuilder();
sb.AppendFormat("registration_id={0}&collapse_key={1}", sRegistrationId, sCollapseKey);
sb.AppendFormat("&delay_while_idle=0&priority=high"); //priority field will not work on this kind of messages
sb.AppendFormat("&data.msg=" + HttpUtility.UrlEncode(sTextToSend)); //To send special characters like ä, ë, arabs...
string msg = sb.ToString();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(GCM_URL);
req.Method = "POST";
req.ContentLength = msg.Length;
req.ContentType = "application/x-www-form-urlencoded";
req.Timeout = 20000;
req.Headers.Add("Authorization:key=" + MyAthorizationKey);
try
{
using (StreamWriter oWriter = new StreamWriter(req.GetRequestStream()))
{
oWriter.Write(msg);
}
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string respData = sr.ReadToEnd();
if (resp.StatusCode == HttpStatusCode.OK) // OK = 200
{
if (respData.StartsWith("id="))
flag = true;
else
sError = respData;
}
else if (resp.StatusCode == HttpStatusCode.InternalServerError) // 500
sError = "Internal server error. Try later.";
else if (resp.StatusCode == HttpStatusCode.ServiceUnavailable) // 503
sError = "Server not available temnporatily. Try later.";
else if (resp.StatusCode == HttpStatusCode.Unauthorized) // 401
sError = "The API Key is not valid.";
else
sError = "Error: " + resp.StatusCode;
}
}
}
catch (WebException e)
{ //The remote server returned an error: (502) Bad Gateway. //Más info: http://stackoverflow.com/questions/2159361/error-502-bad-gateway-when-sending-a-request-with-httpwebrequest-over-ssl
//The remote server returned an error: (500) Internal Server Error. Más info: http://stackoverflow.com/questions/4098945/500-internal-server-error-at-getresponse
sError = "WebException: " + e.ToString();
}
catch (Exception e)
{
sError = "Exception: " + e.ToString();
}
if (flag == true)
return "Ok";
return "Error " + sError;
}