2009/07/29

Prowl / iPhone に C#でPush する

Prowlサーバーに対してのメッセージ通知は、実際のところ httpのPOST/GETで通信します。なので、Prowlサーバーに対して、適切にデータを投げれば簡単にPush通知が実現できます。
以下は C# / .Net での送信例です。エラー処理をちゃんとしてないので注意。

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Net;
using System.Collections.Specialized;

namespace ProwlTest
{
class Program
{
static void Main(string[] args)
{
Encoding enc = Encoding.UTF8;
string url = "https://prowl.weks.net/publicapi/";

try
{
WebClient wc = new WebClient();
NameValueCollection nvc = new NameValueCollection();
wc.Headers.Add("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)");

// API Key の設定
nvc.Add("apikey", "ここに40文字のAPI Keyを記述");

wc.QueryString = nvc;

// API Key が有効か確認
byte[] resData = wc.DownloadData(url + "verify");

// 結果がXML形式で返ってきます
string resText = enc.GetString(resData);

Console.WriteLine(resText);

/* !! ここで返ってきた結果を見てエラー処理すべき !! */


// 実際のメッセージ投稿
// 各データは文字長が決まってるので注意

// priority: An integer value ranging [-2, 2]: Very Low, Moderate, Normal, High, Emergency.
nvc.Add("priority", "0");

// application [256]:The name of your application or the application generating the event.
nvc.Add("application", HttpUtility.UrlEncode("アプリケーション名", enc));

// event [1024]:The name of the event or subject of the event.
nvc.Add("event", "notify");

// description [10000]: A description of the event, generally terse.
nvc.Add("description", HttpUtility.UrlEncode("日本語メッセージはUTF8をUrlエンコードしてやれば通ります。" +
"URLも記述すると、勝手にリンクをはってくれます。" +
"http://prowl.weks.net/", enc));

wc.QueryString = nvc;
resData = wc.DownloadData(url + "add");
resText = enc.GetString(resData);

Console.WriteLine(resText);
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
finally{
wc.Dispose();
}
}
}
}

Prowlサーバーからの結果は、XML形式で返ってきます。
詳細は、API Return format を参照の事。

0 件のコメント:

コメントを投稿