13. 8. 10.

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

push.aspx 파일
1
2
3
4
5
6
7
8
9
10
11
<%@ 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 파일
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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;
    }
}