问题
I'm writing a client that consumes a non-REST API (i.e. GET site.com/gettreasurehunts), which requires that I specify all parameters (even the resource ID) in the request's HTTP body as a custom XML document. I'd like to use Rails and ActiveResource, but I'd be forced to rewrite almost all of ActiveResource's methods.
Is there another, more polished way of achieving the same result, even using another (Ruby) framework?
回答1:
I don't think there is a way to do this with ActiveResource, for these cases I just use Net::HTTP and Nokogiri
回答2:
I would recommend HTTParty, it's pretty flexible and I'm sure capable of handling what you need.
Some examples from the project:
pp HTTParty.get('http://whoismyrepresentative.com/whoismyrep.php?zip=46544')
pp HTTParty.get('http://whoismyrepresentative.com/whoismyrep.php', :query => {:zip => 46544})
@auth = {:username => u, :password => p}
options = { :query => {:status => text}, :basic_auth => @auth }
HTTParty.post('http://www.twitter.com/statuses/update.json', options)
And if you need to POST something in the body of the request, simply add :body => "text" to the options hash.
It's very straightforward to work with and I'm currently using it in place of ActiveResource to consume some REST services from a Rails app.
回答3:
Simple answer, don't. I had a similar problem with ActiveResource, didn't like HTTParty's api (too many class methods), so I rolled my own. Try it out, it's called Wrest. It has partial support for Curl and deserialisation via REXML, LibXML, Nokogiri and JDom out of the box. You can trivially write your own deserialiser too.
Here's an example for the Delicious api:
class Delicious
def initialize(options)
@uri = "https://api.del.icio.us/v1/posts".to_uri(options)
end
def bookmarks(parameters = {})
@uri['/get'].get(parameters)
end
def recent(parameters = {})
@uri['/recent'].get(parameters)
end
def bookmark(parameters)
@uri['/add'].post_form(parameters)
end
def delete(parameters)
@uri['/delete'].delete(parameters)
end
end
account = Delicious.new :username => 'kaiwren', :password => 'fupupp1es'
account.bookmark(
:url => 'http://blog.sidu.in/search/label/ruby',
:description => 'The Ruby related posts on my blog!',
:extended => "All posts tagged with 'ruby'",
:tags => 'ruby hacking'
)
来源:https://stackoverflow.com/questions/1069899/consuming-non-rest-apis-in-rails-with-activeresource