SQLの窓

2013年07月07日


Twitter API の自分のアプリのトークンを使って投稿するだけの class VS2010_Twitter

SkyDrive へ移動( Form 用 )


VS2012 になると、使うクラスや非同期の扱いがかなり変わって来ます。一般的に使用する場合は、ユーザ毎にログインしてもらって専用のアクセストークンを取得してもらうので、WebBrowser コントロールを利用するのが簡単だと思います。(専用のCallback URL も必要になります)

ですが、とりあえず API をテストするのならば自分のアプリのトークンをそのまま使うと簡単です。

VS2010_Twitter.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.Diagnostics;

namespace LBOX_Tool
{
    class VS2010_Twitter
    {
        private string _consumer_key;
        private string _consumer_secret;
        private string _token;
        private string _secret;

        private string _tweet_api = "https://api.twitter.com/1.1/statuses/update.json";

        public VS2010_Twitter (
            string consumer_key,
            string consumer_secret,
            string token,
            string secret
            ) {
                _consumer_key = consumer_key;
                _consumer_secret = consumer_secret;
                _token = token;
                _secret = secret;
        }

        public void Tweet(string text,UploadStringCompletedEventHandler newEvent=null)
        {

            WebClient wc = new WebClient();

            if (newEvent != null)
            {
                wc.UploadStringCompleted += newEvent;
            }

            // ソートされるリスト
            SortedList<string, string> sl = new SortedList<string, string>();
            sl.Add("oauth_consumer_key", _consumer_key);
            sl.Add("oauth_nonce", Nonce());
            sl.Add("oauth_signature_method", "HMAC-SHA1");
            sl.Add("oauth_timestamp", TimeStamp());
            sl.Add("oauth_token", _token);
            sl.Add("oauth_version", "1.0");
            sl.Add("status",  Uri.EscapeDataString(text));

            // http ヘッダ用シグネチャ作成
            string work = "";
            foreach (KeyValuePair<string, string> kvp in sl)
            {
                if (work != "")
                {
                    work += "&";
                }
                work += kvp.Key + "=" + kvp.Value;
            }

            string work2 = "";
            // メソッド
            work2 += "POST" + "&";
            // API URL
            work2 += Uri.EscapeDataString(_tweet_api) + "&";
            // Oauth + データ
            work2 += Uri.EscapeDataString(work);

            // OAuth tool チェック用
            Debug.WriteLine(work2);

            string oauth_signature = Signature(work2);

            // ヘッダ情報を作成
            work = "";
            foreach (KeyValuePair<string, string> kvp in sl)
            {
                // oauth_* のみを使用する
                if (work != "")
                {
                    if (kvp.Key.Substring(0, 6) == "oauth_") {
                        work += ", ";
                    }
                }
                if (kvp.Key.Substring(0, 6) == "oauth_")
                {
                    work += kvp.Key + "=" + Dd(kvp.Value);
                }
            }
            // シグネチャを追加( ヘッダーはソートの必要は無い )
            work += ", oauth_signature=" + Dd(Uri.EscapeDataString(oauth_signature));

            // OAuth tool チェック用
            Debug.WriteLine(work);

            // フォーマットは、 OAuth tool で確認。
            wc.Headers["Authorization"] = "OAuth "  + work;
            // POST 用ヘッダ
            wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";

            // 投稿
            wc.UploadStringAsync(new Uri(_tweet_api), "POST", "status=" + sl["status"] ); 

        }

        // ダブルクォートで挟む
        private string Dd(string base_string)
        {
            return "\"" + base_string + "\"";
        }

        private string Nonce()
        {
            Random rand = new Random();
            int nonce = rand.Next(1000000000);
            return nonce.ToString();
        }

        // タイムスタンプ
        private string TimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        // シグネチャ
        private string Signature(string target)
        {
            string work = _consumer_secret + "&" + _secret;
            byte[] bin = Encoding.UTF8.GetBytes(target);

            HMACSHA1 hmacsha1 = new HMACSHA1();
            hmacsha1.Key = Encoding.UTF8.GetBytes(work);
            byte[] hash = hmacsha1.ComputeHash(bin);

            return Convert.ToBase64String(hash);
        }

    }

}

以下は、実行時のコードです。

Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using LBOX_Tool;

namespace WindowsFormsApplication
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            VS2010_Twitter twitter = 
                new VS2010_Twitter(
                    "Consumer key",
                    "Consumer secret",
                    "Access token",
                    "Access token secret"
                );

            // ただ投稿するだけなら twitter.Tweet(this.textBox1.Text);
            twitter.Tweet(this.textBox1.Text, (object _sender, UploadStringCompletedEventArgs _e) => {
                if (_e.Error == null)
                {
                    // JSON
                    String stringResult = _e.Result;
                    MessageBox.Show(_e.Result);
                }
                else
                {
                    MessageBox.Show("通信エラーが発生しました。\r\n" + _e.Error.Message);
                }

            });

        }
    }
}

エラー処理が単純であれば、ラムダ式が簡単です。

関連する記事

Twitter API の自分のアプリのトークンを使って投稿するだけの class VS2012_Twitter

Twitter API の自分のアプリのトークンを使って投稿するだけの class Android_Twitter

WSH : VBScript と JavaScript で Twitter に投稿する

Twitter アプリの登録方法と、API キーの利用

PHP : Twitter 投稿関数( twitter_update ) / cURL 関数



タグ:twitter API
【VS(C#)の最新記事】
posted by lightbox at 2013-07-07 21:58 | VS(C#) | このブログの読者になる | 更新情報をチェックする
container 終わり



フリーフォントで簡単ロゴ作成
フリーフォントでボタン素材作成
フリーフォントで吹き出し画像作成
フリーフォントではんこ画像作成
ほぼ自由に利用できるフリーフォント
フリーフォントの書体見本とサンプル
画像を大きく見る為のウインドウを開くボタンの作成

CSS ドロップシャドウの参考デモ
イラストAC
ぱくたそ
写真素材 足成
フリーフォント一覧
utf8 文字ツール
右サイド 終わり
base 終わり