уведомление о нажатии iPhone urbanairship

я "m хочу отправить уведомление от своей стороны сервера (c#) с помощью urbanairship API

есть ли какой-либо пример в c#, как сделать это?

спасибо

13
задан avnic 6 March 2010 в 21:19
поделиться

2 ответа

Basically...

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestPostExample
    {
        public static void Main ()
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create ("https://go.urbanairship.com/api/push/");
            // Set the Method property of the request to POST.
            request.Method = "POST";

            // Create POST data and convert it to a byte array. 

разбит на несколько строк, чтобы вы могли его прочитать

            string postData = "{
    "device_tokens": [
        "some device token",
        "another device token"
    ],
    "aliases": [
        "user1",
        "user2"
    ],
    "tags": [
        "tag1",
        "tag2"
    ],
    "schedule_for": [
        "2010-07-27 22:48:00",
        "2010-07-28 22:48:00"
    ],
    "exclude_tokens": [
        "device token you want to skip",
        "another device token you want to skip"
    ],
    "aps": {
         "badge": 10,
         "alert": "Hello from Urban Airship!",
         "sound": "cat.caf"
    }
}";

и затем

            byte[] byteArray = Encoding.UTF8.GetBytes (postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/json";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;

            //Do a http basic authentication somehow
            string username = "<application key from urban airship>";
            string password = "<master secret from urban airship>"; 
            string usernamePassword = username + ":" + password;
            CredentialCache mycache = new CredentialCache();
            mycache.Add( new Uri( "https://go.urbanairship.com/api/push/" ), "Basic", new NetworkCredential( username, password ) );
            request.Credentials = mycache;
            request.Headers.Add( "Authorization", "Basic " + Convert.ToBase64String( new ASCIIEncoding().GetBytes( usernamePassword ) ) );

            // Get the request stream.
            Stream dataStream = request.GetRequestStream ();
            // Write the data to the request stream.
            dataStream.Write (byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close ();
            // Get the response.
            WebResponse response = request.GetResponse ();
            // Display the status.
            Console.WriteLine (((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream ();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader (dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd ();
            // Display the content.
            Console.WriteLine (responseFromServer);
            // Clean up the streams.
            reader.Close ();
            dataStream.Close ();
            response.Close ();
        }
    }
}

См. api docs, msdn и здесь для получения дополнительной информации о https

16
ответ дан 1 December 2019 в 20:56
поделиться

Принятый ответ не работает, вам нужно изменить следующую строку:

request.ContentType = "application/x-www-form-urlencoded";

на

request.ContentType = "application/json";

Полный рабочий код, показанный ниже:

using System;
using System.IO;
using System.Net;
using System.Text;

namespace UrbanAirship_Tes_1
{
    class Program
    {
        public static void Main()
        {

            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("https://go.urbanairship.com/api/push/");
            request.Credentials = new NetworkCredential("pvYMExk3QIO7p2YUs6BBkg", "rO3DsucETRadbbfxHkd6qw");
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            //WRITE JSON DATA TO VARIABLE D
            string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\"6334c016fc643baa340eca25bc661d15055a07b475e9a6108f3f644b15dd05ac\"]}";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/json";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            //            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}
11
ответ дан 1 December 2019 в 20:56
поделиться
Другие вопросы по тегам:

Похожие вопросы: