如何从哈希中向url添加其他参数?例如:
parameters = Hash.new
parameters["special"] = '25235'
parameters["code"] = 62346234
http://127.0.0.1:8000 /api / book_category /? %s参数
require 'httparty'
require 'json'
response = HTTParty.get("http://127.0.0.1:8000/api/book_category/?")
json = JSON.parse(response.body)
puts json
答案 0 :(得分:4)
以下内容应该为您提供一个可用于json查询的有效URI。
require 'httparty'
parameters = {'special' => '512351235','code' => 6126236}
uri = URI.parse('http://127.0.0.1:8000/api/book_category/').tap do |uri|
uri.query = URI.encode_www_form parameters
end
uri.to_s
#=> "http://127.0.0.1:8000/api/book_category/?special=512351235&code=6126236"
Tin Mans对你的问题的评论可能是更好的答案:
require 'httparty'
parameters = {'special' => '512351235','code' => 6126236}
response = HTTParty.get('http://127.0.0.1:8000/api/book_category/', :query => parameters)
json = JSON.parse(response.body)
puts json
答案 1 :(得分:3)
Addressable::URI
类是标准库中URI
模块的绝佳替代,并提供了对URI字符串的这种操作,而无需手动构建和转义查询字符串。
此代码演示
require 'addressable/uri'
include Addressable
uri = URI.parse('http://127.0.0.1:8000/api/book_category/')
parametrs = {}
parametrs["special"] = '25235'
parametrs["code"] = 62346234
uri.query_values = parametrs
puts uri
<强>输出强>
http://127.0.0.1:8000/api/book_category/?code=62346234&special=25235