我是Faraday的新手,并试图学习如何为url params传递一个数组。我的代码如下所示:
require 'faraday'
conn = Faraday.new(:url => 'http://foo.com:8888') do |faraday|
faraday.request :url_encoded
faraday.response :logger
faraday.adapter Faraday.default_adapter
end
response = conn.get '/api/endpoint', { :bar => ['baz', 'qux'] }
response.body
当我调试时,我发现URL被编码为:
INFO -- : get http://foo.com:8888/api/endpoint?bar[]=baz&bar[]=qux
而不是http://foo.com:8888/api/endpoint?bar=baz&bar=qux
。当我传递一系列参数时,如何在没有[]
的情况下对法拉日进行编码?
答案 0 :(得分:2)
我明白为什么现在正在发生这种情况。
此问题实际上已在法拉第版本0.9+上修复,但这只能作为RC使用。
所以有两个选择: 将代码更改为这样(猴子补丁,取自Ruby's Faraday - include the same param multiple times)
require 'faraday'
module Faraday
module Utils
def build_nested_query(value, prefix = nil)
case value
when Array
value.map { |v| build_nested_query(v, "#{prefix}") }.join("&")
when Hash
value.map { |k, v|
build_nested_query(v, prefix ? "#{prefix}%5B#{escape(k)}%5D" : escape(k))
}.join("&")
when NilClass
prefix
else
raise ArgumentError, "value must be a Hash" if prefix.nil?
"#{prefix}=#{escape(value)}"
end
end
end
end
conn = Faraday.new(:url => 'http://foo.com:8888') do |faraday|
faraday.request :url_encoded
faraday.response :logger
faraday.adapter Faraday.default_adapter
end
response = conn.get '/api/endpoint', { :bar => ['baz', 'qux'] }
response.body
或者使用faraday的预发布0.9版本
gem install faraday --pre
并将其添加到您的代码中:
faraday.params_encoder = Faraday::FlatParamsEncoder
这会阻止它添加[]
符号。
答案 1 :(得分:1)
我不能发表评论所以我会这样说:上面的答案对我有用,而且我已经投了赞成票,但这是我的具体例子(我不得不将调用移到FlatParamsEncoder,我用错了方法最初:
#Gemfile
gem 'faraday', '~> 0.9.0.rc5'
#lib/api_wrapper/faraday_adapter.rb
def patch
connection.patch do |req|
req.options.params_encoder = Faraday::FlatParamsEncoder
req.headers['Content-Type'] = 'application/json'
req.url "/api/v1/#{end_point}", @request.params
end
end
def connection
faraday_client = Faraday.new(:url => base_url) do |faraday|
faraday.response :logger if Rails.env.development?
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
end
faraday_client.basic_auth(username, password)
faraday_client
end