gpt4 book ai didi

ruby - 如何使用 HTTParty 发布数组

转载 作者:数据小太阳 更新时间:2023-10-29 08:38:30 26 4
gpt4 key购买 nike

我需要用 HTTParty POST 一个数组.

我的数组是 [1, 2, 3] 并且 API 期望接收表单中的正文

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

这不是很重要,但here's the docs for the API in question .

我目前的解决方案是:

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)

是否有更好的方法(理想的解决方案是我不知道的 HTTParty 功能)?


我尝试了以下方法:

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

但这似乎错误地发送了一个像这样的正文:

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

最佳答案

[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 的值进行编码(除非 HTTPParty 已经为你做了)。所以转义版本看起来像:

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

关于ruby - 如何使用 HTTParty 发布数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19601341/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com