jabsorbのJSON-RPCインターフェイスにRubyで接続してみる
昨日、jabsorbで作成したJSON-RPCインターフェイスにRubyで接続してみる例です。仕様どおりのJSON RPCなので、以下のような感じでさくっと接続できます。
#!/usr/bin/ruby -- require 'rubygems' require 'uri' require 'httpclient' require 'json/lexer' require 'json/objects' # クライアント class JsonRpcClient def initialize( name, host="http://localhost:8080", proxy=ENV["http_proxy"] ) @client = HTTPClient.new( proxy, "JsonClientLib") @client.set_cookie_store("cookie.dat") @name = name @host = host @id = 0 end def method_missing( name, *args ) body = "{ 'id':#{@id+=1},method:#{(@name+"."+name.to_s).to_json},params:#{args.to_json}}" result = @client.post(@host, body ) json = JSON::Lexer.new(result.content).nextvalue if json["error"] raise json["error"]["msg"] else json["result"] end end end #呼び出し例 client = JsonRpcClient.new( "testService", "http://20100102.latest.unageanu-test.appspot.com/jsonrpc" ) puts client.hello( "hello" )
実行結果です。
hello. hello