我想在Asp.Net中實現GCM服務器。有沒有關於它的樣本?我在Android SDK文件夾中查找它,但沒有.Net的示例?谷歌是否有在Asp.Net中的gcm服務器的示例?
是否有任何男孩知道.Net示例?
我想在Asp.Net中實現GCM服務器。有沒有關於它的樣本?我在Android SDK文件夾中查找它,但沒有.Net的示例?谷歌是否有在Asp.Net中的gcm服務器的示例?
是否有任何男孩知道.Net示例?
試試這個:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Collections.Specialized;
public class AndroidGCMPushNotification
{
public AndroidGCMPushNotification()
{
//
// TODO: Add constructor logic here
//
}
public string SendNotification(string deviceId, string message)
{
string GoogleAppID = "GGOGLE_API_KEY";
var SENDER_ID = "SENDER_ID/PROJECT_NUMBER";
var value = message;
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "collapse_key=score_update&time_to_live=108&
delay_while_idle=1&data.message=" + value + "&data.time=" +
System.DateTime.Now.ToString() + "registration_id=" + deviceId + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
}
你可以通過設備ID和信息調用sendNotification的功能。
AndroidGCMPushNotification apnGCM = new AndroidGCMPushNotification();
string strResponse =
apnGCM.SendNotification("DEVICE_ID",
"Test Push Notification message ");
@Najj Makhoul itried但我得到了一個錯誤401:未經授權如何處理這個 –
有一個在這條線的一個小錯誤:
string postData = "collapse_key=score_update&time_to_live=108&
delay_while_idle=1&data.message=" + value + "&data.time=" +
System.DateTime.Now.ToString() + "registration_id=" + deviceId + "";
「&」 的參數registration_id前失蹤,所以& registration_id是正確的。
樣品完美。只要確保讓你在服務器密鑰:
string GoogleAppID = "GGOGLE_API_KEY";
http://stackoverflow.com/a/14293642/115145 – CommonsWare
http://stackoverflow.com/questions/11543527/google-cloud-messaging-server-側邊代碼在C - 銳 –