从Rails 3中的控制器操作中获取REST请求

时间:2012-09-21 01:01:23

标签: ruby-on-rails ruby ruby-on-rails-3 rest amazon-web-services

我需要在控制器的Update操作中使用REST请求。这是Amazon Payments Marketplace API。以下是他们的例子。我如何在控制器内调用它并处理响应?以下也是回复。任何帮助非常感谢。

Sample REST Request

https://fps.sandbox.amazonaws.com?
Action=Settle
&AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE
&ReserveTransactionId=14GKD9GE66FAA63E6O6B2JDPZKN53LZ7F22
&SignatureMethod=HmacSHA256
&SignatureVersion=2
&Signature=SJJLsIBghi7VIycBjX7c3hnfgZ%2FBvZbzqLtAZXDL8ys%3D
&Timestamp=2009-10-06T07%3A53%3A11.750Z
&TransactionAmount.CurrencyCode=USD
&TransactionAmount.Value=1
&Version=2008-09-17

对REST请求的示例响应

<SettleResponse xmlns="http://fps.amazonaws.com/doc/2008-09-17/">
  <SettleResult>
    <TransactionId>14GKD9GE66FAA63E6O6B2JDPZKN53LZ7F22</TransactionId>
    <TransactionStatus>Pending</TransactionStatus>
  </SettleResult>
  <ResponseMetadata>
    <RequestId>9ed2008b-b230-4ed0-9210-095f77fc2359:0</RequestId>
  </ResponseMetadata>
</SettleResponse>

1 个答案:

答案 0 :(得分:0)

您可以直接使用与ruby捆绑在一起的Net::HTTP执行此操作:

require "net/http"
require "open-uri"

uri = URI.parse("http://www.google.com")
response = Net::HTTP.get_response(uri)
=> #<Net::HTTPOK 200 OK readbody=true>

然后得到回复的正文:

body = response.body
#=> "<!doctype html><html itemscope=\"itemscope\" ...

如果您想做更复杂的事情,我建议您使用HTTP client gemHTTPartyfaraday。有很多examples using HTTParty包含aaws的示例。

如果繁重只是在事情的响应解析方面,你可以使用nokogiri

require 'nokogiri'

doc = Nokogiri::HTTP(body)
doc.search('h1').text
#=> "Google"