2010年7月15日

[C#] - Plurk API library 初探

Plurk API使用教學(登入,發噗)

最近放假沒事都在玩噗...所以也玩玩噗的API...

plurk機器人是怎麼製作的呢?

方法有兩種:
1.Plurk API推出前,有一些玩家自己做了簡單的功能!(非官方版本)
2.Plurk API(official version)

今天要介紹的是official version.

工欲善其事,必先利其器!!Plurk API如何取得?

到下列網址去申請API Key
http://www.plurk.com/API







接著就能取得一串勒勒長的key

還會使用到一個Json的套件!
http://james.newtonking.com/projects/json-net.aspx

這是Plurk的資料傳送格式!!

在開始實作之前先大致瞭解了一下plurk API的函式(絕大部份是用GET來做的)

所以我們要先寫一個Http Get的函式,以便送出請求!

public CookieContainer session = new CookieContainer();//session
public string Get(string url)
        {
            string request = null;
            try
            {
                HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
                WebReq.CookieContainer = session;
                WebReq.Method = "GET";
                HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
                StreamReader sr = new StreamReader(WebResp.GetResponseStream(), Encoding.Default);
                request = sr.ReadToEnd().Trim();
            }
            catch (WebException ex)
            {
            }
            return request;
        }


接下來開始實作login,依然會使用到上述的Get函式

string API_KEY = "*********************************";
public bool Plurk_login(string username, string password)//Plurk login 登入成功回傳true
        {
            if (Get("http://www.plurk.com/API/Users/login?api_key=" + API_KEY + "&username=" + username + "&password=" + password) == null)
                return false;
            else
                return true;
        }

如果Get成功,則會回傳true,失敗則傳回false!

登入成功之後,就可以發噗哩!!!發噗也不困難!!

public bool Plurk_PostMessage(string content,string qualifier,string lang)
{
        //content(內容),qulifier(噗最前方的字),lang(語言):tr_ch(繁中)
 string add_message = "api_key=" + API_KEY + "&content="+content+ "&qualifier=" +qualifier+"&lang="+lang;
        if(Get("http://www.plurk.com/API/Timeline/plurkAdd?" + add_message)==null))
    return false;
        else
           return true;
}

除了發出除了上述的參數以外,還有一些非必要參數!可以參考下列網址:
http://www.plurk.com/API#/API/Timeline/plurkAdd
P.S.發噗有防洪機制!!所以三分鐘才能發一次!!

另外有一點,plurk API會回傳他的錯誤訊息!!不過礙於HttpWebResponse只能傳回100,200的值

似乎沒辦法傳回錯誤時所回傳的值!!

若要達到這樣的話!!可能會需要自行撰寫一個HttpWebResponse!!


2010/07/14 By YC

轉載請附上作者!

1 則留言:

  1. 你很認真哦!

    看來你應該也是受了祕密的影響吧!!!


    加油哦!!

    小佩

    回覆刪除