Click here to Skip to main content
15,881,455 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Please help me, I have a problem to push notification for android from ASP.NET webservice (VB.NET).
this is my code.
VB
Public sApplicationID As String = "YYY....ZZZ"
Public sSENDER_ID As String = "222...555"

<WebMethod()> _
Public Function SendMessage(ByVal RegistrationID As String, ByVal Message As String) As String
        Dim regid As String = RegistrationID
        Dim tRequest As WebRequest
        tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send")
        tRequest.Method = "post"
        'tRequest.ContentType = " application/json"
        tRequest.ContentType = " application/x-www-form-urlencoded"
        tRequest.Headers.Add(String.Format("Authorization: key={0}", sApplicationID))

        tRequest.Headers.Add(String.Format("Sender: id={0}", sSENDER_ID))

        Dim postData As String = "{""collapse_key"":""score_update"",""time_to_live"":108,""delay_while_idle"":1,""data"":{""message"":""" & Convert.ToString(Message) & """,""time"":""" & System.DateTime.Now.ToString() & """},""registration_ids"":" & regid & "}"
        Console.WriteLine(postData)
        Dim byteArray As [Byte]() = Encoding.UTF8.GetBytes(postData)
        tRequest.ContentLength = byteArray.Length

        Dim dataStream As Stream = tRequest.GetRequestStream()
        dataStream.Write(byteArray, 0, byteArray.Length)
        dataStream.Close()

        Dim tResponse As WebResponse = tRequest.GetResponse()

        dataStream = tResponse.GetResponseStream()

        Dim tReader As New StreamReader(dataStream)

        Dim sResponseFromServer As [String] = tReader.ReadToEnd()

        tReader.Close()
        dataStream.Close()
        tResponse.Close()

        Return sResponseFromServer
    End Function



I was testing this service but I always getting error message
System.Net.WebException: The remote server returned an error: (401) Unauthorized.
at System.Net.HttpWebRequest.GetResponse()


Please Help me..
Posted

1 solution

This worked for me in C#

C#
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace ENSource.Infrastructure
{
    public static class AndroidGCM
    {
        public static string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
        {
            //Delegate Modeling to Validate Server Certificate
            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(HttpRequestHeader.Authorization, string.Format("key={0}", apiKey));
            Request.ContentLength = byteArray.Length;

            //Create Stream to Write Byte Array
            Stream dataStream = Request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            try
            {
                //Post a Message
                WebResponse Response = Request.GetResponse();

                //Check the response status
                HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;

                string errorMessage = string.Empty;
                if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
                {
                    errorMessage = "Unauthorized - need new token";

                }
                else if (!ResponseCode.Equals(HttpStatusCode.OK))
                {
                    errorMessage = "Response from web service isn't OK";
                }

                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;

        }
    }    
}


You can use it as under

C#
/*

GCM gcm = new GCM();

            var applicationID = "******wdVY8xs";
            string deviceId = "A*****EAsEDth";
            string message = "hey ,some text message";
            string tickerText = "example test GCM";
            string contentTitle = "content title GCM";
            string postData =
            "{ \"registration_ids\": [ \"" + deviceId + "\" ], " +
              "\"data\": {\"tickerText\":\"" + tickerText + "\", " +
                         "\"contentTitle\":\"" + contentTitle + "\", " +
                         "\"message\": \"" + message + "\"}}";

            var X = gcm.SendGCMNotification(applicationID, postData);
*/


You can convert the above C# code to VB.net by using some online convertor.
Hope this helps
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900