RubyでTwitter APIを使い、Twitterにログインするプログラムを書いてみた。ユーザー名を表示するようにした。emailとpasswordが正しいことを信じてるプログラムなので間違った情報を入れると正常に動かない
require 'net/http' require 'rexml/document' email = '*********@*******.ne.jp' password = "*******" class User attr_reader :id attr_reader :name attr_reader :screen_name attr_reader :url attr_reader :followers_count attr_reader :friends_count def initialize(id, name, screen_name, url, followers_count, friends_count) @id = id @name = name @screen_name = screen_name @url = url @followes_count = followers_count @friends_count = friends_count end end class Twitter attr_reader :user attr_reader :cookie def login(username, password) request = Net::HTTP::Get.new('/account/verify_credentials.xml') request.basic_auth(username, password) http = Net::HTTP.start('twitter.com') response = http.request(request) doc = REXML::Document.new(response.body) id = doc.elements['/user/id'].text() name = doc.elements['/user/name'].text() screen_name = doc.elements['/user/screen_name'].text() url = doc.elements['/user/url'].text() followers_count = doc.elements['/user/followers_count'].text() friends_count = doc.elements['/user/friends_count'].text() @cookie = response['Set-Cookie'] @user = User.new(id, name, screen_name, url, followers_count, friends_count) return @user end end twitter = Twitter.new user = twitter.login(email, password) puts user.name
参考
net/http - Rubyリファレンスマニュアル
http://www.ruby-lang.org/ja/man/html/net_http.html
Twitter API 仕様書 (勝手に日本語訳シリーズ)
http://watcher.moe-nifty.com/memo/2007/04/twitter_api.html