如何向URL添加额外参数?- 编码URL

3
如何从哈希中添加额外的参数到URL?例如:
parameters = Hash.new
parameters["special"] = '25235'
parameters["code"] = 62346234

http://127.0.0.1:8000/api/book_category/?%s参数

该网址是一个API接口,其中%s参数可以根据需要进行替换。
require 'httparty'
require 'json'

response = HTTParty.get("http://127.0.0.1:8000/api/book_category/?")


json = JSON.parse(response.body)
puts json

4
当参数为Array类时,parametrs["special"] = '25235' 是无效的。请注意修正拼写错误。 - Torimus
HTTParty支持getpost:query参数,这使得添加正确编码的参数变得微不足道。请参见https://github.com/jnunemaker/httparty/blob/master/examples/rubyurl.rb,因此不需要更复杂的内容。 - the Tin Man
2个回答

4
以下内容将为您提供一个有效的URI,您可以用于JSON查询。
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"

铁人关于你问题的评论可能是更好的答案:

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
如果您正在使用URI.encode_www_form,那么请完全使用URI。解析URL,然后也使用query=方法。 - the Tin Man

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

+1 给 Addressable::URI。它是一个很棒的工具。 - the Tin Man

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接