From 0c0b284c98498459c78880197db1c804c6f12d57 Mon Sep 17 00:00:00 2001 From: joshua stein Date: Wed, 25 Sep 2024 10:37:14 -0500 Subject: [PATCH] Sponge: properly encode POST data Should fix #1081 --- extras/sponge.rb | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/extras/sponge.rb b/extras/sponge.rb index 24a646bd8c..864482bbe9 100644 --- a/extras/sponge.rb +++ b/extras/sponge.rb @@ -180,7 +180,7 @@ def fetch(url, method = :get, fields = nil, raw_post_data = nil, headers = {}, l post_data = raw_post_data send_headers["Content-Type"] = "application/x-www-form-urlencoded" else - post_data = fields.map { |k, v| "#{k}=#{v}" }.join("&") + post_data = encode_fields(fields) end send_headers["Content-Length"] = post_data.length.to_s @@ -263,4 +263,26 @@ def dputs(string) puts string end end + + def encode_fields(fields) + fields.map { |k, v| + if v.is_a?(Hash) + # :user => { :name => "hi", :age => "1" } + # becomes + # user[hame]=hi and user[age]=1 + v.map { |vk, vv| + [ CGI.escape("#{k}[#{vk}]"), CGI.escape(vv.to_s) ].join("=") + } + elsif v.is_a?(Array) + # :user => [ "one", "two" ] + # becomes + # user[]=one and user[]=two + v.map{|vv| + [ CGI.escape("#{k}[]"), CGI.escape(vv.to_s) ].join("=") + } + else + [ CGI.escape(k.to_s), CGI.escape(v.to_s) ].join("=") + end + }.flatten.join("&") + end end