はてなフォトライフのAtomAPIをRubyでほげほげしてみた
はてなフォトライフAtomAPIについてははてダキーワードを参照の事。
その1: net/httpで叩いてみる
WSSE認証用のライブラリがあるので導入する。
sudo gem install wsee
で、コードは以下。
require 'socket' require 'net/http' require 'rubygems' require 'wsse' #config uri = 'f.hatena.ne.jp' id = 'id' pass = 'pass' #wsse auth http = Net::HTTP.start(uri,80) res = http.get('/atom/feed',{'X-WSSE' => WSSE::header(id,pass)})
ここで指定してる /atom/feed は投稿された写真のうち最近のエントリをAtomフィードで取得するためのエンドポイント。はてなでフィードしているatomフィードと同じものが返ってくるらしい。res.bodyにStringクラスで入っているので、Xml-Simpleなどを使ってハッシュなんかにすると扱いやすいんじゃないかな。
ただ、これの場合postするときがクソ面倒そう...。
その2: atomutilを使ってみる。
atom/atompubを扱うライブラリがあるので導入する。
sudo gem install atomutil
で、コードは以下。
require 'rubygems' require 'atomutil' #config feed_uri = 'http://f.hatena.ne.jp/atom/feed' id = 'id' pass = 'pass' #create client auth = Atompub::Auth::Wsse.new :username => id, :password => pass client = Atompub::Client.new :auth => auth #get feed feed = client.get_feed(feed_uri)
動作自体はその1とほぼ同じだけど、返ってきたものは feed.elem に REXML::Element クラスで入っている。
atomutil使う利点はpost時。リクエスト用のXMLを書くのが楽。
require "rubygems" require "atomutil" require "pathname" #create post xml image = Pathname.new("hogehoge.jpg") entry = Atom::Entry.new({ :title => image.basename.to_s, :updated => Time.now, :content => Atom::Content.new do |c| c.body = [image.read].pack('m') c.type = "image/jpeg" c.set_attr(:mode, "base64") end, }) #config post_uri = 'http://f.hatena.ne.jp/atom/post' id = 'id' pass = 'pass' #create client auth = Atompub::Auth::Wsse.new :username => id, :password => pass client = Atompub::Client.new :auth => auth #post data client.create_entry(post_uri, entry)