我通过 POST 从我的 .NET 应用程序向 GCM 发送数据。第一个我的 android 设备得到一个 ID,它 POST 到我的 ASP.NET 应用程序。然后我的网站上有一个简单的按钮“发送消息”,它以 JSON 格式将数据发布到 GCM。
Private Function SendNotification(ByVal JSonData As String) As String
ServicePointManager.ServerCertificateValidationCallback = Function(sender As Object, certificate As X509Certificate, chain As X509Chain, sslPolicyErrors As SslPolicyErrors) True
'/// Creating POST.
Dim request As WebRequest = WebRequest.Create("https://android.googleapis.com/gcm/send")
request.Method = "POST"
request.ContentType = "Content-Type: application/json"
request.Headers.Add(String.Format("Authorization: key={0}", MyAPIKey))
'/// Converting data to byte array.
Dim postData As String = JSonData
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
'/// Post
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
'/// Response
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Return responseFromServer
End Function
JsonData byval 包含:
{ "collapse_key":"DitIsEenUniekeIdentifier",
"time_to_live":108,
"delay_while_idle":true,
"data": {
"MessageId":1,
"TestInformation":"BlieBloeBlaaaa tadaaa!"
},
"registration_ids":["APA91bFYQbSDzQDsoRrR3bnKtH_o72kQ7oiArg79WNz8qeCVoe6Kxu_BdcVftX1pGOfwLCLZbf_D3b7-V2yIaVasHxWXbn35nJO1bIiDzF84ifCHKJTyK3KiZmHZwAJliVIFcZFEVEsKTRiXWgpm9WWmnPrsbKvASy6FZyv4Eyfv-K526Q38Hjs"]
}"
当我检查谷歌开发页面时,这似乎是正确的。 http://developer.android.com/google/gcm/gcm.html
我之前可以使用相同的功能发送到 GCM,但当时我使用的是纯文本。这是第一次尝试Json。我更改了帖子的标题。request.ContentType = "Content-Type: application/json" 在 request.ContentType = "application/x-www-form-urlencoded" 之前
我以纯文本形式发送的数据:
Dim postData As String = String.Format("registration_id={0}&data.payload={1}&collapse_key={2}", ReceiverKey, Message, collaspeKey)
我从 GCM 得到的错误消息: MissingRegistration 根据谷歌:
注册号
检查请求是否包含注册 ID(在纯文本消息中的 registration_id 参数中,或在 JSON 中的 registration_ids 字段中)。当错误代码为 MissingRegistration 时发生。
非常感谢任何帮助。
亲切的问候。