2

I need to POST an array with HTTParty.

My array is [1, 2, 3] and the API expects to receive the body to be in the form

"story_hash=1&story_hash=2&story_hash=3"

It's not really important but here's the docs for the API in question.

The solution I have at the moment is:

params = [1, 2, 3].inject('') { |memo, h| memo += "&story_hash=#{h}" }
# Strip the first '&'
params.slice!(0)

options = { body: params }
HTTParty.post('/reader/mark_story_hashes_as_read', options)

Is there a better way (the ideal solution would be a feature of HTTParty that I just don't know of)?


I tried the following method:

options = {
  body: { story_hash: [1, 2, 3] }
}
HTTParty.post('/reader/mark_story_hashes_as_read', options)

But that seems to erroneously send a body like this:

"story_hash[]=1&story_hash[]=2&story_hash[]=3"
4

3 回答 3

2
[1, 2, 3].map{|h| "story_hash=#{h}"}.join("&")
#=> "story_hash=1&story_hash=2&story_hash=3"

我还建议使用CGI.escape(h.to_s)而不是h,它会对 url 的值进行编码(除非HTTParty已经为您这样做了)。所以转义版本看起来像:

[1, 2, 3].map{|h| "story_hash=#{CGI.escape(h.to_s)}"}.join("&")
#=> "story_hash=1&story_hash=2&story_hash=3"
于 2013-10-26T00:22:07.303 回答
1

您可以为此目的使用HTTParty::HashConversions.to_params方法

require "httparty"
HTTParty::HashConversions.to_params((1..3).map { |x| ["story_hash", x] })
# => story_hash=1&story_hash=2&story_hash=3
于 2013-10-26T08:44:01.060 回答
1

我同意@tihom,只是想补充一点,如果您要多次使用它,最好覆盖 query_string_normalizer 方法。

class ServiceWrapper
  include HTTParty

  query_string_normalizer proc { |query|
    query.map do |key, value|
      value.map {|v| "#{key}=#{v}"}
    end.join('&')
  }
end
于 2013-10-26T00:41:00.980 回答