13. 8. 10.

안드로이드 C#.NET PUSH 서버

push.aspx 파일
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="push.aspx.cs" Inherits="mobile_push" %>

<!DOCTYPE html>
<html>
<head>
    <title>푸쉬 전송 TEST</title>
</head>
<body>
<asp:Literal ID="SendResult" runat="server" />
</body>
</html>


push.aspx.cs 파일
using System;
using System.Net.Security;
using System.Net;
using System.Text;
using System.IO;
using System.Security.Cryptography.X509Certificates;

public partial class mobile_push : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {


        // 브라우저APIkey
        string BrowserAPIKey = Request.QueryString["ApiKey"];
        // BrowserAPIKey  = "AIzaSyBi0pn1ckaJhRL9kK3mbwsHzk7x0fdE_Z8";

        // regId(받을사람이 지급받은 registration_ids - 여러명일 경우 배열로 받아처리하면 될 듯 최대 1000)
        string RegId = Request.QueryString["RegId"];
        // RegId = "APA91bFNkzpbgBJnWkDgyGmU0XsF8ZLMAEhVaAtcbf9po8_i1GoA4JNt4HiUc6xScBMEOoJMIHHybZECIns9e2EF4AGalfOgZqwmQIEUG1UpVk08nTapx0iY17vOELD_9wIQTUdRwUsR";

        // 알림명
        string tickerText = Request.QueryString["Ticker"];
        // tickerText = "알림테스트";

        // 알림 제목
        string contentTitle = Request.QueryString["Title"];
        // contentTitle = "알림제목";

        // 알림 내용
        string message = Request.QueryString["Msg"];
        // message = "안녕하세요~~~푸쉬입니다.";

        string postData = "";
        postData += "{";
        postData += "  \"registration_ids\": [ \"" + RegId + "\" ]";
        postData += ", \"data\": {";
        postData += "                 \"tickerText\":\"" + tickerText + "\"";
        postData += "               , \"contentTitle\":\"" + contentTitle + "\"";
        postData += "               , \"message\": \"" + message + "\"";
        postData += "            }";
        postData += "}";

        string response = SendGCMNotification(BrowserAPIKey, postData);

        SendResult.Text = response;

    }



    private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
    {
        ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
        //  MESSAGE CONTENT
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        //  CREATE REQUEST
        HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
        Request.Method = "POST";
        Request.KeepAlive = false;
        Request.ContentType = postDataContentType;
        Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
        Request.ContentLength = byteArray.Length;

        Stream dataStream = Request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        //  SEND MESSAGE
        try
        {
            WebResponse Response = Request.GetResponse();
            HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
            if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
            {
                var text = "Unauthorized - need new token";
                Console.Write(text);
            }
            else if (!ResponseCode.Equals(HttpStatusCode.OK))
            {
                var text = "Response from web service isn't OK";
                Console.Write(text);
            }

            StreamReader Reader = new StreamReader(Response.GetResponseStream());
            string responseLine = Reader.ReadToEnd();
            Reader.Close();

            return responseLine;
        }
        catch (Exception e)
        {

        }
        return "Error";

    }

    public static bool ValidateServerCertificate(object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }
}

댓글 2개: