【问题标题】:Passing array of id's as query parameter of net/http传递 id 数组作为 net/http 的查询参数
【发布时间】:2021-12-25 15:41:38
【问题描述】:

我想使用标准 Ruby 客户端 net/http 发出类似的 GET 请求:

stores/?ids=2,24,13

我正在尝试这样做,其中 store_ids 是一个 id 数组,但它不起作用。如果我将单个 id 作为 ids 的参数传递,则响应是正确的。

def get_stores_info
  uri = URI(BASE_URL)
  params = { ids: store_ids, offset: DEFAULT_OFFSET, limit: DEFAULT_LIMIT }
  uri.query = URI.encode_www_form(params)
  response = Net::HTTP.get_response(uri).body
  result = JSON.parse response
end

【问题讨论】:

  • 您希望 id 像这样吗? ids=2,24,13?你是如何在后端处理的?通常,id[]=1&id[]=24&id[]=13 应该在查询字符串中发送,以便 Rails 以... params[:id] = [2,24,13] 的形式获取参数。
  • 我无法控制后端,所以我需要像这样构建请求:ds=2,24,13

标签: ruby net-http


【解决方案1】:

您可以将store_ids 转换为字符串:

store_ids = [2,24,13]
params = { ids: store_ids.join(','), offset: 0, limit: 25 }

# these are to see that it works.
encoded = URI.encode_www_form(params) # => "ids=%5B2%2C+24%2C+13%5D&offset=0&limit=25"
CGI.unescape(encoded) # => ids=2,24,13&offset=0&limit=25

这是Replit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 2022-12-15
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    相关资源
    最近更新 更多