提取返回字符串参数值

时间:2013-11-03 21:23:24

标签: ruby ruby-on-rails-3

我的请求看起来像这样;

url = "https://api-3t.sandbox.paypal.com/nvp?METHOD=DoExpressCheckoutPayment&TOKEN=#{transaction.token}
                        &PAYERID=#{transaction.payer_id}&PAYMENTREQUEST_n_PAYMENTACTION=sale"
url = CGI.escape(url)
uri = URI(url)
res = Net::HTTP.get_response(uri)

res.body看起来像这样; TOKEN=EC%2d7UM71457T34680821&TIMESTAMP=2013%2d11%2d03T21%3a19%3a11Z&CORRELATIONID=3b73c396244ff&ACK=Success&VERSION=98&BUILD=8334781

如何从字符串中获取TOKENACK值?我不确定params在这里工作吗? 有什么想法吗?

1 个答案:

答案 0 :(得分:2)

正文是URI编码的,就像GET(或一些POST)参数一样。您可以通过以下方式手动解压缩它:

require 'uri'

# body takes place of res.body for this example
body = 'TOKEN=EC%2d7UM71457T34680821&TIMESTAMP=2013%2d11%2d03' +    
  'T21%3a19%3a11Z&CORRELATIONID=3b73c396244ff&AC' + 
  'K=Success&VERSION=98&BUILD=8334781'

# First split into key/value pairs, and use inject to start building a hash
results = body.split('&').inject( {} ) do |hash,kv| 

  # Split each key/value pair
  k,v = kv.split('=').map do |uri_encoded_value| 
    # Decode - innermost loop, because it may contain encoded '&' or '='
    URI.decode(uri_encoded_value)
  end

  # Add to hash we are building with inject
  hash[k] = v
  hash
end

=> {"TOKEN"=>"EC-7UM71457T34680821", "TIMESTAMP"=>"2013-11-03T21:19:11Z",
 "CORRELATIONID"=>"3b73c396244ff", "ACK"=>"Success", "VERSION"=>"98", 
 "BUILD"=>"8334781"}

实际上,虽然URI可以为您做几乎所有这些(并且比上面更好地处理格式的变化),但使用decode_www_form类方法。

params = {}
URI.decode_www_form( body ).each do |k,v|
  params[k] = v
end
params
=> {"TOKEN"=>"EC-7UM71457T34680821", "TIMESTAMP"=>"2013-11-03T21:19:11Z",
 "CORRELATIONID"=>"3b73c396244ff", "ACK"=>"Success", "VERSION"=>"98", 
 "BUILD"=>"8334781"}