发送使用数组变量HTTParty [英] Sending array variables using HTTParty
问题描述
我要送使用HTTParty POST请求。一所需的变量是一个数组。这是code我使用派:
=响应URL HTTParty.post,:身体=>
{关键=>'XYZ123',
内容=>
[{地名=>中的占位符
placecontent=>中样本内容}],
等}
该API需要看到:
内容:
{
地名:占位
placecontent:样本内容
}
]
然而,当我检查了API接收日志的请求,我看到我的code是生产:
内容:
{
地名:占位
},
{
placecontent:样本内容
}
]
我怎么能在两个被拆停止数组记录?
感谢。
编辑:
的code的期望输出是等价的:
默认情况下, HTTParty
使用的 HashConversions
来转换哈希
身体参数:
例子:
{:名称=> 鲍勃,
:地址=> {
:街道=> 111红宝石大道,
:城市=> 红宝石中环,
:手机=> ['111-111-1111','222-222-2222']
}
} .to_params
#=> NAME =鲍勃&放大器;解决[城市] =红宝石Central&address[phones][]=111-111-1111&address[phones][]=222-222-2222&address[street]=111
红宝石大道。
块引用>您可以通过使用<一个用自己的转换器重写此href=\"http://www.ruby-doc.org/gems/docs/h/httparty2-0.7.10/HTTParty/ClassMethods.html#method-i-query_string_normalizer\"相对=nofollow>
HTTParty.query_string_normalizer
:
覆盖的方式查询字符串进行归一化。有助于覆盖
默认轨正常化阵列查询。
有关的查询:
得到'/',:查询=&GT; {:selected_ids =&GT; [1,2,3]}
默认的查询字符串正规化回报:
/ selected_ids [] = 1&安培; selected_ids [] = 2及selected_ids [] = 3
让我们把它改成这样:
/ selected_ids = 1&安培; selected_ids = 2及selected_ids = 3
传递一个Proc到接受查询产生的查询归。
@example修改阵列查询字符串
类ServiceWrapper
包括HTTParty query_string_normalizer PROC {|查询|
query.map做|键,值|
value.map {| V | #{}键#= {V}
end.join('和;')
}
结束
@param [PROC]正规化自定义查询字符串正规化。 @yield [哈希,
字符串]查询字符串@yieldreturn [数组]数组,稍后将
加入了与'和;
块引用>或者只是通过它在你的选择:
=响应URL HTTParty.post,:身体=&GT;
{关键=&GT;'XYZ123',
内容=&GT;
[{地名=&gt;中的占位符
placecontent=&gt;中样本内容}]},
:query_string_normalizer =&GT; - &GT; (H){...自己的实现在这里...}要得到一个序列化
A [1] = VAL1&放大器;一个[2] = val2的
而不是A [] = VAL1&放大器;一个[ ] = val2的
您可以创建自己的HashConversions
基础上的当前类MyHashConversions 高清to_params(散)
PARAMS = {hash.map | K,V | normalize_param(K,V)}。加入
params.chop! #尾随&安培;
PARAMS
结束 DEF normalize_param(键,值)
参数=''
堆栈= [] 如果value.is_a?(阵列) ####的变化是这里 参数&LT;&LT; value.each_with_index.map {|元素,我| normalize_param(#{}键[#{I}],元素)}。加入 ####
ELSIF value.is_a?(井)
堆叠式和LT;&LT; [键,值]
其他
参数&LT;&LT; #{}键=#{URI.en code(value.to_s,Regexp.new([^#{URI :: PATTERN ::毫无保留}]))}&安培;
结束 stack.each做|父母,哈希|
hash.each做| K,V |
如果v.is_a?(井)
堆叠式和LT;&LT; [#{}家长[#[KP}],V]
其他
参数&LT;&LT; normalize_param(#{}家长[#[KP}],第五章)
结束
结束
结束 参数
结束
结束在code以上没有进行测试,但如果它的工作原理,并具有足够通用的,你可以考虑分叉项目和github上,使得固定在那里,所以将工作开箱:)
I'm sending a POST request using HTTParty. One of the variables required is an array. This is the code I'm using to send:
response = HTTParty.post url, :body => {"key"=>'XYZ123', "content"=> [{"placename"=>"placeholder", "placecontent"=>"sample content"}], etc. }
The API needs to see:
"content": [ { "placename": "placeholder", "placecontent": "sample content" } ],
However, when I check the request received logs on the API, I see that my code is producing:
"content": [ { "placename": "placeholder" }, { "placecontent": "sample content" } ],
How can I stop the array record from being split in two?
Thanks.
EDIT: The desired output of the code is the equivalent of:
...&content[0][placename]=placeholder&content[0][placecontent]=sample%20content...
解决方案By default,
HTTParty
usesHashConversions
to convert aHash
body to parameters:Examples:
{ :name => "Bob", :address => { :street => '111 Ruby Ave.', :city => 'Ruby Central', :phones => ['111-111-1111', '222-222-2222'] } }.to_params #=> "name=Bob&address[city]=Ruby Central&address[phones][]=111-111-1111&address[phones][]=222-222-2222&address[street]=111
Ruby Ave."
You can override this with your own convertor by using
HTTParty.query_string_normalizer
:Override the way query strings are normalized. Helpful for overriding the default rails normalization of Array queries.
For a query:
get '/', :query => {:selected_ids => [1,2,3]}
The default query string normalizer returns:
/?selected_ids[]=1&selected_ids[]=2&selected_ids[]=3
Let’s change it to this:
/?selected_ids=1&selected_ids=2&selected_ids=3
Pass a Proc to the query normalizer which accepts the yielded query.
@example Modifying Array query strings
class ServiceWrapper include HTTParty query_string_normalizer proc { |query| query.map do |key, value| value.map {|v| "#{key}=#{v}"} end.join('&') } end
@param [Proc] normalizer custom query string normalizer. @yield [Hash, String] query string @yieldreturn [Array] an array that will later be joined with ‘&’
or simply pass it in your options:
response = HTTParty.post url, :body => {"key"=>'XYZ123', "content"=> [{"placename"=>"placeholder", "placecontent"=>"sample content"}]}, :query_string_normalizer => -> (h) { ... your own implementation here ...}
To get a serialization of
a[1]=val1&a[2]=val2
instead ofa[]=val1&a[]=val2
you can create your ownHashConversions
based on the current oneclass MyHashConversions def to_params(hash) params = hash.map { |k,v| normalize_param(k,v) }.join params.chop! # trailing & params end def normalize_param(key, value) param = '' stack = [] if value.is_a?(Array) #### THE CHANGE IS HERE param << value.each_with_index.map { |element, i| normalize_param("#{key}[#{i}]", element) }.join #### elsif value.is_a?(Hash) stack << [key,value] else param << "#{key}=#{URI.encode(value.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))}&" end stack.each do |parent, hash| hash.each do |k, v| if v.is_a?(Hash) stack << ["#{parent}[#{k}]", v] else param << normalize_param("#{parent}[#{k}]", v) end end end param end end
The code above is not tested, but if it works, and is generic enough, you might consider forking the project and github, making the fix there, so it will work out of the box :)
这篇关于发送使用数组变量HTTParty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!