我正在为我的 Android 应用程序使用 Google Cloud Messaging (GCM) 服务。我已经按照所有规则实施了它,并且它有效。嗯,差不多。
大多数情况下,我会说在 60-70% 的情况下,我可以使用 google 网页上讨论的 web 服务从我的服务器成功发送 GCM 消息。
正常情况下,我从 webservice 收到以下回复,这表明我成功发送了 GCM 消息:
{
"multicast_id":8378088572050307085,
"success":1,
"failure":0,
"canonical_ids":0,
"results":
[
{
"message_id":"0:1363080282442710%7c4250c100000031"
}
]
}
这就是说:一切正常,消息已发送。
但是,在许多情况下,我在调用 Web 服务时会收到 HTTP 错误,上面写着:
无法从传输连接读取数据:已建立的连接被主机中的软件中止。
这是 .NET 消息,告诉我调用 Web 服务(使用 HttpWebRequest 和 POST)失败。
这是一些显示问题的日志消息:
这是我用来调用 WS 的代码:
public static string SendMessage(string registrationId, string command, string extra, bool retry)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
request.Method = PostWebRequest;
request.KeepAlive = false;
GCMPostPacket json = new GCMPostPacket()
{
collapse_key = "1",
time_to_live = 60,
registration_ids = new List<string>(new string[] { registrationId }),
data = new GcmData()
{
message = command,
misc = extra
}
};
// Converting to JSON string
string jsonString = SICJsonProtocol.JSONHelper.Serialize<GCMPostPacket>(json);
byte[] byteArray = Encoding.UTF8.GetBytes(jsonString);
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
request.ProtocolVersion = HttpVersion.Version10;
request.Headers.Add(HttpRequestHeader.Authorization, "key=" + "MyVerySecretKey");
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
using (WebResponse response = request.GetResponse())
{
HttpStatusCode responseCode = ((HttpWebResponse)response).StatusCode;
if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
{
Console.WriteLine("Unauthorized - need new token");
}
else if (!responseCode.Equals(HttpStatusCode.OK))
{
Console.WriteLine("Response from web service not OK :");
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
}
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseLine = reader.ReadLine();
Console.WriteLine("************************");
Console.WriteLine("GCM send: " + responseCode + " | " + responseLine);
// This is the log shown in the image above
SRef.main.gui.ServiceUpdate("GCM send: " + responseCode + " | " + responseLine);
reader.Close();
response.Close();
return responseLine;
}
}
catch (Exception e)
{
// This is the log shown in the image above
SRef.main.gui.ServiceUpdate("Failed send GCM, " + (retry ? "retrying in 20 sec" : "not retrying") + ". Error=" + e.Message);
if (retry)
{
System.Threading.ThreadPool.QueueUserWorkItem(delegate(object obj)
{
try
{
System.Threading.Thread.Sleep(20000);
SendMessage(registrationId, command, extra, false);
}
catch (Exception ex)
{
}
});
}
return null;
}
}
任何人都可以看到我是否做错了什么,或者我是否缺少一般的东西?