11. January 2013
Jake
ソフトウェア開発
.NETの標準以外に Newtonsoft のJSON.NETを使用します。http://james.newtonking.com/pages/json-net.aspx
使い方は
var container = new Google.GoogleCloudMessaging.Container {
RegistrationIds = new String [] { "APA*******PQZQ" },
Data = new { message = "Hello World!" }
};
var response = Google.GoogleCloudMessaging.Broadcast( "AIz************", container );
のようになります。
------------------------------
using System;
using System.Net;
using Newtonsoft.Json;
namespace Google
{
public class GoogleCloudMessaging
{
public class Container
{
[JsonProperty("registration_ids")]
public String[] RegistrationIds { get; set; }
[JsonProperty("collapse_key", NullValueHandling=NullValueHandling.Ignore )]
public String CollapseKey { get; set; }
[JsonProperty("data", NullValueHandling = NullValueHandling.Ignore)]
public object Data { get; set; }
[JsonProperty("delay_while_idle", NullValueHandling = NullValueHandling.Ignore)]
public Boolean? DelayWhileIdle { get; set; }
[JsonProperty("time_to_live", NullValueHandling = NullValueHandling.Ignore)]
public int? TimeToLive { get; set; }
[JsonProperty("restricted_package_name", NullValueHandling = NullValueHandling.Ignore)]
public String RestrictedPackageName { get; set; }
[JsonProperty("dry_run", NullValueHandling = NullValueHandling.Ignore)]
public Boolean? DryRun { get; set; }
}
public class Response
{
[JsonProperty("multicast_id")]
public String MulticastId { get; set; }
[JsonProperty("success")]
public int Success { get; set; }
[JsonProperty("failure")]
public int Failure { get; set; }
[JsonProperty("canonical_ids")]
public int CanonicalIds { get; set; }
[JsonProperty("results")]
public Result[] Results { get; set; }
}
public class Result
{
[JsonProperty("message_id")]
public String MessageId { get; set; }
[JsonProperty("registration_id")]
public String RegistrationId { get; set; }
[JsonProperty("error")]
public String Error { get; set; }
}
static public Response Broadcast(String API_KEY, Container container)
{
var request = WebRequest.Create("https://android.googleapis.com/gcm/send");
var json = Newtonsoft.Json.JsonConvert.SerializeObject(container);
using( WebClient web = new WebClient()){
web.Headers.Add("Authorization", "key=" + API_KEY );
web.Headers.Add("Content-Type", "application/json");
byte[] result = web.UploadData("https://android.googleapis.com/gcm/send", "POST", System.Text.Encoding.UTF8.GetBytes(json) );
String resultString = System.Text.Encoding.UTF8.GetString(result);
var response = Newtonsoft.Json.JsonConvert.DeserializeObject<Response>( resultString );
return response;
}
}
}
}