Net::HTTP 对于标准用例可能相当麻烦!
7 回答
如果您只需要处理 REST,那么rest-client库非常棒。
如果您使用的 API 不是完全 RESTful——或者即使它们是——HTTParty真的值得一试。它简化了 REST API 以及非 RESTful Web API 的使用。查看此代码(从上面的链接复制):
require 'rubygems'
require 'httparty'
class Representative
include HTTParty
format :xml
def self.find_by_zip(zip)
get('http://whoismyrepresentative.com/whoismyrep.php', :query => {:zip => zip})
end
end
puts Representative.find_by_zip(46544).inspect
# {"result"=>{"n"=>"1", "rep"=>{"name"=>"Joe Donnelly", "district"=>"2", "office"=>"1218 Longworth", "phone"=>"(202) 225-3915", "link"=>"http://donnelly.house.gov/", "state"=>"IN"}}}
rest-open-uri是在RESTful Web 服务一书中大量使用的一种。
gem install rest-open-uri
示例用法:
response = open('https://wherever/foo',
:method => :put,
:http_basic_authentication => ['my-user', 'my-passwd'],
:body => 'payload')
puts response.read
我是rest-client的忠实粉丝,它在不妨碍您的实施的情况下足够有用。它智能地处理异常,并支持开箱即用的日志记录和身份验证。
HyperactiveResource还处于起步阶段,但看起来还不错。
这就是我使用的:http ://rubyforge.org/projects/restful-rails/ 。
看看 github 上 asplake 的(即我的)describe_routes 和 path-to projects/gems(我似乎无法从这里链接到。Path-to 使用 HTTParty,而不是像其他的一些硬编码 URL这个问题的答案, 它使用 describe_routes 提供的元数据. 在 positiveincline.com 上有几篇描述这些宝石的文章, 其中与您的问题最相关的是Nested path-to/ describe_routes 和 HTTParty .
好吧,只要你在 Rails 上,总会有 ActiveResource :)