Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save siliconbrain/3c123cb8d4eb49cc41d1 to your computer and use it in GitHub Desktop.
Save siliconbrain/3c123cb8d4eb49cc41d1 to your computer and use it in GitHub Desktop.
minimal HTTP GCM application server in C#
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace Siliconbrain.Utilities
{
public class GoogleCloudMessagingApplicationServer : IDisposable
{
private static readonly Uri _sendUri = new Uri("https://android.googleapis.com/gcm/send");
private readonly HttpClient _httpClient;
public GoogleCloudMessagingApplicationServer(string apiKey)
: this(SetAuthorization(new HttpClient(), apiKey))
{
}
public GoogleCloudMessagingApplicationServer(HttpClient httpClient)
{
_httpClient = httpClient;
}
static HttpClient SetAuthorization(HttpClient httpClient, string apiKey)
{
var success = httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + apiKey);
System.Diagnostics.Debug.Assert(success);
return httpClient;
}
public async Task SendMessageAsync<TMessageData>(IEnumerable<string> registrationIds, TMessageData messageData)
{
var requestBody = new
{
registration_ids = registrationIds,
data = messageData,
};
await _httpClient.PostAsJsonAsync(_sendUri, requestBody);
}
public void Dispose()
{
_httpClient.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment