Created
April 16, 2015 23:23
-
-
Save siliconbrain/3c123cb8d4eb49cc41d1 to your computer and use it in GitHub Desktop.
minimal HTTP GCM application server in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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