1

我想在 Asp.Net中实现一个GCM服务器。有没有关于它的样本?我在 Android SDK 文件夹中寻找它,但没有 .Net 的示例?

有男孩知道.Net 样本吗?

4

2 回答 2

0

这一行有一个小错误:

 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前缺少“&”,所以®istration_id是正确的。

样品完美运行。只需确保将您的服务器密钥放在:

string GoogleAppID = "GGOGLE_API_KEY";
于 2013-11-29T16:16:53.323 回答
0

尝试这个 :

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 ");
于 2013-08-24T15:21:48.467 回答