您能提供一个简单的代码(或链接),通过下游HTTP JSON 从我的C#服务器向Android设备发送简单消息吗?
我使用下一个简单的c#代码使用下游HTTP纯文本发送邮件。但我需要使用 JSON 来执行此操作,因为我需要使用优先级字段。
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;
}
答案 0 :(得分:0)
private string SendMessageUsingGCM(String sRegistrationId, string sTextToSend, string sCollapseKey)
{
String GCM_URL = @"https://gcm-http.googleapis.com/gcm/send";
bool flag = false;
string sError = "";
string msg = "{";
msg += "\"to\": \"" + sRegistrationId+ "\",";
msg += "\"collapse_key\": \"" + sCollapseKey + "\", ";
msg += "\"priority\": \"high\",";
msg += "\"data\": {\"msg\": \"" + sTextToSend+ "\" }";
msg += "}";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(GCM_URL);
req.Method = "POST";
req.ContentLength = msg.Length;
req.ContentType = "application/json";
req.Timeout = 2000;
req.Headers.Add("Authorization:key=" + MyAthorizationKey);
try
{
Byte[] byteArray = Encoding.UTF8.GetBytes(msg);
req.ContentLength = byteArray.Length; //<--To send special characters like ä, ë, arabs... http://stackoverflow.com/questions/32537219/error-httpwebrequest-bytes-to-be-written-to-the-stream-exceed-the-content-len
Stream writer = req.GetRequestStream();
writer.Write(byteArray, 0, byteArray.Length);
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;
}