正文是 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"}